Entity Framwork Core 数据注解(Data Annotations)使用方法

在Entity Framework Core中,数据注解(Data Annotations)是通过在实体类的属性上使用特性(Attributes)来配置实体与数据库之间的映射关系的一种方式。这种方式比较直观且易于理解,特别适用于简单的配置需求。下面是一些使用数据注解配置实体的C#示例:

1. 配置主键

public class Blog
{
    [Key]
    public int BlogId { get; set; }
    
    public string Url { get; set; }
    
    // 其他属性...
}

 

2. 配置列名

public class Blog
{
    public int BlogId { get; set; }
    
    [Column("BlogURL")]
    public string Url { get; set; }
    
    // 其他属性...
}

 

3. 配置必需字段和最大长度

public class Blog
{
    public int BlogId { get; set; }
    
    [Required]
    [MaxLength(200)]
    public string Title { get; set; }
    
    // 其他属性...
}

 

4. 配置数据类型和精度

public class Product
{
    public int ProductId { get; set; }
    
    public string Name { get; set; }
    
    [Column(TypeName = "decimal(18, 2)")]
    public decimal Price { get; set; }
    
    // 其他属性...
}

 

5. 配置并发令牌

public class Blog
{
    public int BlogId { get; set; }
    
    public string Url { get; set; }
    
    [Timestamp]
    public byte[] RowVersion { get; set; }
    
    // 其他属性...
}

 

6. 配置导航属性和外键

public class Blog
{
    public int BlogId { get; set; }
    
    public string Url { get; set; }
    
    public List<Post> Posts { get; set; }
}

 

public class Post
{
    public int PostId { get; set; }
    
    public string Title { get; set; }
    
    public string Content { get; set; }
    
    public int BlogId { get; set; }
    
    [ForeignKey("BlogId")]
    public Blog Blog { get; set; }
}

 

7. 配置不映射到数据库的属性

public class Blog
{
    public int BlogId { get; set; }
    
    public string Url { get; set; }
    
    [NotMapped]
    public string DisplayUrl => $"http://example.com/{Url}";
}

 

8. 配置索引

public class Blog
{
    public int BlogId { get; set; }
    
    [Index]
    public string Url { get; set; }
    
    // 其他属性...
}

 

9. 配置唯一约束

public class User
{
    public int UserId { get; set; }
    
    [Index(IsUnique = true)]
    public string Email { get; set; }
    
    // 其他属性...
}

 

在使用数据注解时,您不需要在DbContextOnModelCreating方法中显式配置实体,因为EF Core会在运行时自动解析这些特性并应用相应的配置。不过,对于更复杂的配置需求,您可能需要结合使用Fluent API以获得更大的灵活性和控制力。在实际项目中,通常建议根据具体情况选择合适的配置方式。

posted @ 2024-05-20 15:17  剑小秀  阅读(178)  评论(0)    收藏  举报