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 @   剑小秀  阅读(111)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
点击右上角即可分享
微信分享提示