fluent AI的常用方法

Fluent API是Entity Framework Core的一个功能,它提供了一组可以以流式、链式调用的方法来配置EF的模型。它给予你对模型的完全控制权,高于数据注解(Data Annotations)的优先级。它通常用于DbContext中的OnModelCreating方法里。以下是一些常用的Fluent API配置方法的例子:

配置主键

csharp

modelBuilder.Entity<YourEntity>().HasKey(e => e.Id);

配置关系

一对多

csharp

modelBuilder.Entity<Parent>()
    .HasMany(p => p.Children)
    .WithOne(c => c.Parent)
    .HasForeignKey(c => c.ParentId);

一对一

csharp

modelBuilder.Entity<Parent>()
    .HasOne(p => p.Child)
    .WithOne(c => c.Parent)
    .HasForeignKey<Child>(c => c.ParentId);

配置字段

csharp

modelBuilder.Entity<YourEntity>()
    .Property(e => e.Name)
    .IsRequired(); // 字段是必需的

设置字符串长度

csharp

modelBuilder.Entity<YourEntity>()
    .Property(e => e.Name)
    .HasMaxLength(200); // 设置最大长度

配置列名和数据类型

csharp

modelBuilder.Entity<YourEntity>()
    .Property(e => e.Name)
    .HasColumnName("EntityName")
    .HasColumnType("varchar(200)"); // 设置列名和类型

联合主键

csharp

modelBuilder.Entity<YourEntity>()
    .HasKey(e => new { e.Id, e.AnotherKey }); // 联合主键

配置索引

csharp

modelBuilder.Entity<YourEntity>()
    .HasIndex(e => e.UniqueProperty)
    .IsUnique(); // 设置唯一索引

自定义表名与架构

csharp

modelBuilder.Entity<YourEntity>()
    .ToTable("CustomName", schema: "CustomSchema"); // 设置表名和架构名

这些仅仅是Fluent API部分功能的简要介绍。Fluent API的优势在于它提供了比数据注解更加灵活的配置方式,尤其在处理复杂的实体关系映射以及继承关系时显得尤为重要。这也意味着代码会比起数据注解长和复杂,但是你获得了更多的控制力和灵活性。在实践中,Fluent API经常与数据注解混用 —— 对于简单的配置使用数据注解,而对于更复杂的情况则使用Fluent API。

posted @ 2024-04-18 23:49  GroundSoft  阅读(63)  评论(0编辑  收藏  举报