首页 > 解决方案 > EF Core 使用 Fluent API 按类型配置实体属性

问题描述

我有一个具有多个相同类型属性的实体。我想在同一个表中包含该类型的所有属性。

OwnsOne(o => o.property)您可以通过调用实体来获取同一个表中的各个属性。但我想在该类型的所有属性上执行此操作。

假设我们有以下(工作)示例:

public class Animal 
{
    public int Id { get; set; }
    public ProvidedLength LengthAtBirth { get; set; }
    public ProvidedLength LengthAtDead { get; set; }
}

public class ProvidedLength 
{
    public DateTime SubmissionDate { get; set; }
    public string Unit { get; set; }
    public string Length { get; set; }
}

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }

    public DbSet<Animal> Animals { get; set; }

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

class AnimalConfiguration : IEntityTypeConfiguration<Animal>
{
    public void Configure(EntityTypeBuilder<Animal> builder)
    {
        // TODO: Apply the OwnsOne configuration all properties of the "ProvidedLength" type
        builder.OwnsOne(a => a.LengthAtBirth);
        builder.OwnsOne(a => a.LengthAtDead);
    }
}

我不想调用每个属性,而是想为ProvidedLength类型执行此操作。

我试过builder.OwnsOne<ProvidedLength>()and builderBuilder.Entity<ProvidedLength>.OwnsOne(),但在这两种情况下你都需要提供 navigationProperty。

标签: c#entity-frameworkentity-framework-coreef-fluent-api

解决方案


推荐阅读