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; } // 其他属性... }
在使用数据注解时,您不需要在DbContext
的OnModelCreating
方法中显式配置实体,因为EF Core会在运行时自动解析这些特性并应用相应的配置。不过,对于更复杂的配置需求,您可能需要结合使用Fluent API以获得更大的灵活性和控制力。在实际项目中,通常建议根据具体情况选择合适的配置方式。
分类:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?