gpt4 book ai didi

c# - EF Core 通过抽象基类的流畅映射实现 Table-Per-Concrete-Type

转载 作者:太空狗 更新时间:2023-10-30 01:32:43 25 4
gpt4 key购买 nike

假设您有两个从抽象基类派生的实体,并且您想要实现 Table-Per-Concrete-Type。实体如下:

public abstract class EntityBase
{
public int Id { get; set; }

public string CreatedBy { get; set; }

public DateTime CreatedAt { get; set; }
}

public class Person : EntityBase
{
public string Name { get; set; }
}
public class PersonStatus : EntityBase
{
public string Title { get; set; }
}

并且您不想在抽象基类 (EntityBase) 中使用属性,您希望为所有实体映射 dbcontext 中的 EntityBase 类仅一次。如何更改以下代码:

public class PeopleDbContext : DbContext
{
public DbSet<Person> People { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

// Entity base class mapping(only once)

modelBuilder.Entity<Person>(e =>
{
e.Property(x => x.Name)
.IsRequired()
.HasMaxLength(100);
});
modelBuilder.Entity<PersonStatus>(e =>
{
e.Property(x => x.Title)
.IsRequired()
.HasMaxLength(100);
});
}

}

最佳答案

Here是你问题的答案..

您需要为您的基类编写配置:

public class EntityBaseConfiguration<TBase> : IEntityTypeConfiguration<TBase>
where TBase : EntityBase
{
public virtual void Configure(EntityTypeBuilder<TBase> builder)
{
builder.HasKey(b => b.Id);
builder.Property(b => b.CreatedBy)
.HasColumnType("varchar(50)");
builder.Property(b => b.CreatedAt)
.HasColumnType("datetime2");
}
}

之后,您可以为每个继承自 EntityBase 的表编写具体的配置类,如下所示:

public class PersonConfig : BaseConfig<Person>
{
public override void Configure(EntityTypeBuilder<Person> builder)
{
base.Configure(builder);
builder.Property(e => e.Name)
.HasColumnType("varchar(100)")
.IsRequired();
}
}

要在 dbContext 中调用您的配置,您可以调用 ApplyConfiguration:

public class PeopleDbContext : DbContext
{
public DbSet<Person> People { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new PersonConfig());
}
}

关于c# - EF Core 通过抽象基类的流畅映射实现 Table-Per-Concrete-Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36354127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com