EF Core Data Annotations怎么用 EF Core数据注解使用方法

来源:这里教程网 时间:2026-02-21 17:35:10 作者:

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 Orders { get; set; } }

[ForeignKey("CustomerId")] 告诉 EF Core:
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 支持属性、只读属性(
get
only)、只写属性(
set
only)
常用于 DTO 转换、前端展示字段、临时计算值等场景

基本上就这些。数据注解够用、轻量、易读,但不支持复合主键、复杂索引、继承映射等高级功能——那些得靠 Fluent API。日常开发中,建议先用注解搭骨架,再按需用

OnModelCreating
补充细节。

相关推荐