.NET核心实体框架 - 歧视器TPH



我当前正在尝试写入从抽象基类继承的表。当我尝试执行此操作时,我会收到以下错误(ContactMethod属性是歧视者(:

System.Data.SqlClient.SqlException: Invalid column name 'ContactMethod'.

emailContactDetails.cs:

public class EmailContactDetail : ContactDetail
{
    [ApiMember(Description = "The Contact Method")]
    public override ContactMethod ContactMethod => ContactMethod.Email;
    [ApiMember(Description = "Email Address")]
    public string EmailAddress { get; set; }
}

emailContactDetailConfiguration.cs:

public class EmailContactDetailsConfiguration : IEntityTypeConfiguration<EmailContactDetail>
{
    public void Configure(EntityTypeBuilder<EmailContactDetail> builder) => Configure(builder, "dbo");
    public void Configure(EntityTypeBuilder<EmailContactDetail> builder, string schema)
    {
        builder.Property(x => x.EmailAddress).HasColumnName("EmailAddress").HasColumnType("nvarchar(255)");
    }
}

ContactDetail.cs:

public abstract class ContactDetail
{
    [ApiMember(Description = "The Identifier")]
    public Guid Id { get; set; }
    [ApiMember(Description = "The Contact Method")]
    public virtual ContactMethod ContactMethod { get; set; }
}

ContactDetailConfiguration.cs

public class ContactDetailsConfiguration : IEntityTypeConfiguration<ContactDetail>
{
    public void Configure(EntityTypeBuilder<ContactDetail> builder) => Configure(builder, "dbo");
    public void Configure(EntityTypeBuilder<ContactDetail> builder, string schema)
    {
        builder.ToTable("ContactDetails", schema);
        // Table per hierarchy. all subclasses share the same db table for performance.
        builder.HasDiscriminator(x => x.ContactMethod)
            .HasValue<EmailContactDetail>(ContactMethod.Email);
        builder.Property(x => x.Id).HasColumnName("Id").IsRequired().HasColumnType("uniqueidentifier").ValueGeneratedOnAdd();
    }
}

我尝试通过将以下内容添加到ContactDetailConfiguration.cs文件:

来隐藏" ContactMethod":
builder.Ignore(x => x.ContactMethod);

完成后,我最终会出现以下错误

The entity type 'EmailContactDetail' is part of a hierarchy, but does not have a discriminator property configured.

您不应该隐藏EF中配置为TPH歧视器的属性,因为它对于EF核心实现TPH策略至关重要。

初始错误仅表示您的模型和数据库是不同步的。的确,按照惯例,EF核心使用string阴影属性和列为Discriminator。但是,HasDiscriminator Fluent API的全部目的是允许更改鉴别属性/列类型,并将其映射到实体模型的现有属性。

这里是这种情况。您已经告诉EF Core将现有属性ContactMethod用作鉴别器,因此EF Core在数据库表中寻找名为ContactMethod的列。因此,要解决问题,只需从模型中更新数据库(更改模型时使用通常的过程 - 添加新迁移,更新数据库等(。

相关内容

  • 没有找到相关文章

最新更新