.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中的验证框架等复用。
相关推荐
deriva13 小时前
windows系统安装linux并docker部署.netcore项目
linux·docker·.netcore
温暖的苹果2 天前
【.Net runtime】coreclr(.Net应用启动过程)
c#·.net·.netcore
AI题库2 天前
1.3 ABP MVC开发环境搭建指南:从零开始快速上手
asp.net·mvc·.net·.netcore
时光追逐者4 天前
ASP.NET Core 依赖注入的三种服务生命周期
后端·c#·asp.net·.net·.netcore
武藤一雄5 天前
C# 中线程安全都有哪些
后端·安全·微软·c#·.net·.netcore·线程
csdn_aspnet5 天前
.NET 8 Web 应用、Web API 和 RabbitMQ
rabbitmq·.netcore·.net8
温暖的苹果5 天前
【.Net runtime】corehost(.NET 应用启动过程)
c#·.net·.netcore
csdn_aspnet6 天前
使用 Windows 客户端的 RabbitMQ Messaging for .NET 8 Web API 第 2 部分
windows·rabbitmq·.netcore·.net8
csdn_aspnet6 天前
使用 Windows 客户端的 RabbitMQ Messaging for .NET 8 Web API 第 1 部分
rabbitmq·.net·.netcore·.net8
csdn_aspnet6 天前
ASP.NET Core:创建并验证文档上的数字签名
.netcore·数字签名