.NET Core FluentAPI

目录

约定配置

主要规则

两种配置方式

[Data Annotation](#Data Annotation)

[Fluent API](#Fluent API)

[Fluent API配置](#Fluent API配置)

[Fluent API众多方法](#Fluent API众多方法)

选择


约定配置

主要规则

  1. 表名采用DbContext中的对应的DbSet的属性名。
  2. 数据表列的名字采用实体类属性的名字,列的数据类型采用和实体类属性类型最兼容的类型。
  3. 数据表列的可空性取决于对应实体类属性的可空性。
  4. 名字为Id的属性为主键,如果主键为short, int 或者 long类型,则默认采用自增字段,如果主键为Guid类型,则默认采用默认的Guid生成机制生成主键值。

两种配置方式

Data Annotation

把配置以特性(Annotation)的形式标注在实体类中。

优点:简单;缺点:耦合。

cs 复制代码
[Table("T_Books")]
public class Book
{
}
Fluent API

把配置写到单独的配置类中。

缺点:复杂;优点:解耦。

cs 复制代码
builder.ToTable("T_Books");
Fluent API配置
  1. 视图与实体类映射:
    modelBuilder.Entity<Blog>().ToView("blogsView");
  2. 排除属性映射:
    modelBuilder.Entity<Blog>().Ignore(b => b. Name2);
  3. 配置列名:
    modelBuilder.Entity<Blog>().Property(b=>b.BlogId).HasColumnName("blog_id");
  4. 配置列数据类型:
    builder.Property(e => e.Title) .HasColumnType("varchar(200)")
  5. 配置主键:
    默认把名字为Id或者"实体类型+Id"的属性作为主键,可以用HasKey()来配置其他属性作为主键。modelBuilder.Entity<Student>().HasKey(c => c.Number);支持复合主键,但是不建议使用。
  6. 生成列的值:
    modelBuilder.Entity<Student>().Property(b => b.Number).ValueGeneratedOnAdd();
  7. 设置默认值:
    modelBuilder.Entity<Student>().Property(b => b.Age).HasDefaultValue(6);
  8. 索引:
    modelBuilder.Entity<Blog>().HasIndex(b => b.Url);
  9. 复合索引:
    modelBuilder.Entity<Person>().HasIndex(p => new { p.FirstName, p.LastName });
  10. 唯一索引:IsUnique();聚集索引:IsClustered()
  11. 用EF Core太多高级特性的时候谨慎,尽量不要和业务逻辑混合在一起,以免"不能自拔"。比如Ignore、Shadow、Table Splitting等......
Fluent API众多方法

Fluent API中很多方法都有多个重载方法。比如HasIndex、Property()。

把Number属性定义为索引,下面两种方法都可以:

cs 复制代码
builder.HasIndex("Number");
builder.HasIndex(b=>b.Number);

推荐使用HasIndex(b=>b.Number)、Property(b => b.Number)这样的写法,因为这样利用的是C#的强类型检查机制

选择
  1. Data Annotation 、Fluent API大部分功能重叠。可以混用,但是不建议混用。
  2. 有人建议混用,即用了Data Annotation 的简单,又用到Fluent API的强大,而且实体类上标注的[MaxLength(50)]、[Required]等标注可以被ASP.NET Core中的验证框架等复用。
相关推荐
时光追逐者10 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 51 期(2025年8.18-8.24)
c#·.net·.netcore·.net core
norsd4 天前
Linux CentOS 安装 .net core 3.1
linux·centos·.netcore
时光追逐者6 天前
C#/.NET/.NET Core技术前沿周刊 | 第 50 期(2025年8.11-8.17)
c#·.net·.netcore·.net core
切糕师学AI7 天前
.net core web程序如何设置redis预热?
redis·.netcore
csdn_aspnet8 天前
ASP.NET Core 中的多租户 SaaS 应用程序
.netcore·saas
时光追逐者13 天前
C#/.NET/.NET Core技术前沿周刊 | 第 49 期(2025年8.1-8.10)
c#·.net·.netcore
切糕师学AI13 天前
在 .NET Core 5.0 中启用 Gzip 压缩 Response
.netcore
周杰伦fans14 天前
.NET Core MVC中CSHTML
mvc·.netcore
爱吃香蕉的阿豪21 天前
乐思 AI 智能识别平台(基于 YOLO,.NET+Vue3 开发)开源指南
人工智能·yolo·开源·aigc·.netcore
时光追逐者21 天前
C#/.NET/.NET Core优秀项目和框架2025年7月简报
c#·.net·.netcore