EF Core 数据注解(Data Annotations)是一组写在实体类和属性上的特性(Attributes),让 EF Core 在运行时自动理解如何把你的 C# 类映射到数据库表结构、字段约束、关系等。它简单直观,适合中小型项目或快速原型开发。
基础配置:表名与主键
用 [Table] 指定实体映射的数据库表名,可选带 Schema:
[Table("users", Schema = "auth")]
public class User
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
[Table("users")] → 映射到 users表;加
Schema = "auth"则生成在
auth.users下 [Key] 标记主键字段,EF Core 默认识别
Id或
ClassNameId,但显式标注更清晰可靠
字段级控制:长度、空值与类型
对字符串等属性加验证和数据库约束注解:
public class Product
{
[Key]
public int Id { get; set; }
<pre class="brush:php;toolbar:false;">[Required] // NOT NULL
[MaxLength(100)] // nvarchar(100)
public string Name { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal Price { get; set; }
[StringLength(500)]
public string Description { get; set; }}
[Required] 强制非空,生成NOT NULL列 [MaxLength(n)] 和 [StringLength(n)] 效果类似,都限制最大长度;前者更常用,后者兼容 ASP.NET 验证 [Column(TypeName = "...")] 精确控制数据库列类型,比如
varchar、
datetime2、
decimal(18,2)
关系与外键配置
用 [ForeignKey] 明确声明外键属性,并配合导航属性使用:
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
<pre class="brush:php;toolbar:false;">[ForeignKey("CustomerId")]
public Customer Customer { get; set; }}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public List
Customer导航属性由
CustomerId字段驱动 若属性名符合约定(如
CustomerId对应
Customer),可省略该注解;但显式写上更易维护 注意:
[ForeignKey]参数是外键属性名(字符串),不是导航属性名
忽略字段与只读计算属性
用 [NotMapped] 排除不存入数据库的字段:
public class User
{
public int Id { get; set; }
public string Email { get; set; }
<pre class="brush:php;toolbar:false;">[NotMapped]
public string DisplayName => $"User-{Email.Split('@')[0]}";
[NotMapped]
public DateTime LocalCreatedAt { get; set; }}
所有标了 [NotMapped] 的属性,不会出现在迁移生成的表中,也不会参与 INSERT/UPDATE 支持属性、只读属性(getonly)、只写属性(
setonly) 常用于 DTO 转换、前端展示字段、临时计算值等场景
基本上就这些。数据注解够用、轻量、易读,但不支持复合主键、复杂索引、继承映射等高级功能——那些得靠 Fluent API。日常开发中,建议先用注解搭骨架,再按需用
OnModelCreating补充细节。
