属性配置
实体属性配置是定义模型与数据库映射的核心,EFCore 提供两种方式:数据注解和 Fluent API
1. 数据注解(Data Annotations)
通过特性(Attributes)直接在实体类上声明配置,适合简单场景。
public class Product{
[Key] // 主键
public int Id { get; set; }
[Required, MaxLength(100)] // 非空且最大长度100
public string Name { get; set; }
[ForeignKey("CategoryId")] // 外键
public int CategoryId { get; set; }
public Category Category { get; set; }
}
常用注解:
[Key]:主键
[Required]:非空约束
[MaxLength(length)]:最大长度
[ForeignKey]:外键关系
[Table("TableName")]:自定义表名
2. Fluent API
在 DbContext 的 OnModelCreating 方法中配置,提供更灵活的方式。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>(entity =>{
entity.HasKey(p => p.Id); // 主键
entity.Property(p => p.Name)
.IsRequired()
.HasMaxLength(100);
entity.HasOne(p => p.Category) // 一对一/多关系
.WithMany(c => c.Products)
.HasForeignKey(p => p.CategoryId);
});
}
常用配置方法:
HasKey():定义主键
Property().IsRequired():非空约束
HasIndex():创建索引
HasOne().WithMany():配置导航关系
优势:
集中管理配置,避免污染实体类。
支持复杂配置(如复合主键、继承映射)。