.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中的验证框架等复用。
相关推荐
weixin_379880923 天前
.Net Core WebApi集成Swagger
java·服务器·.netcore
The Future is mine5 天前
.Net Core 在Linux系统下创建服务
linux·运维·.netcore
*长铗归来*6 天前
ASP.NET Core Web API 中控制器操作的返回类型及Swagger
后端·c#·asp.net·.netcore
IDOlaoluo6 天前
VS2017 安装 .NET Core 2.2 SDK 教程(包括 dotnet-sdk-2.2.108-win-x64.exe 安装步骤)
.netcore
csdn_aspnet13 天前
使用 Entity Framework Code First 方法创建 ASP.NET Core 5.0 Web API
.netcore·webapi
小先生81213 天前
.NET Core项目中 Serilog日志文件配置
c#·.netcore
爱吃香蕉的阿豪13 天前
.NET Core 中 System.Text.Json 与 Newtonsoft.Json 深度对比:用法、性能与场景选型
数据库·json·.netcore
csdn_aspnet13 天前
ASP.NET Core 10.0 的主要变化
.netcore
csdn_aspnet16 天前
在 C# .NETCore 中使用 MongoDB(第 1 部分):驱动程序基础知识和插入文档
mongodb·.netcore
csdn_aspnet17 天前
在 C# .NETCore 中使用 MongoDB(第 3 部分):跳过、排序、限制和投影
mongodb·c#·.netcore