【问题标题】:.Ignore() throwing exception after migration to EFCore 3.1.Ignore() 迁移到 EFCore 3.1 后抛出异常
【发布时间】:2020-03-07 16:56:30
【问题描述】:

在迁移到 EFcore 3.1(迁移前使用 2.2)之前,我有这个代码块工作,现在它抛出以下异常:'The type 'ProfileEnum' cannot be configured as non-owned because an owned entity type with the same name already exists.'

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

     modelBuilder.Entity<ProfileEnum>()
            .Ignore(p => p.Name);
}

场景是:ProfileEnum 是一种复杂类型,我使用以下块映射到 User 类

public class UserConfig : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.HasKey(x => x.UserId);

        builder.Property(x => x.Name)
            .HasMaxLength(200);

        builder.Property(x => x.DocumentNumber)
            .HasMaxLength(50);

        **builder.OwnsOne(x => x.Profile, profile =>
        {
            profile.Property(c => c.Value)
            .IsRequired()
            .HasColumnName("ProfileId")
            .HasColumnType("integer");
        });**
     }
 }


public class ProfileEnum
{
    public static ProfileEnum CompanyAdmin = new ProfileEnum(1, "CompanyAdmin");
    public static ProfileEnum Admin { get; } = new ProfileEnum(2, "Admin");
    public static ProfileEnum PowerUser { get; } = new ProfileEnum(3, "PowerUser");
    public static ProfileEnum Standard { get; } = new ProfileEnum(4, "Standard");
    private ProfileEnum(int val, string name)
    {
        Value = val;
        Name = name;
    }
}

【问题讨论】:

  • ProfileEnum 类型不完整,缺少属性。但我不清楚你将如何使用这种类型。如果 EF 无法设置 Name 并且名称/值组合似乎是固定的,为什么会有包含 name 的构造函数?为什么不使用常规枚举?顺便说一句,错误是由modelBuilder.Entity&lt;ProfileEnum&gt;() 将类型注册为实体引起的。

标签: c# ef-code-first entity ef-core-2.2 ef-core-3.1


【解决方案1】:

我最终在实体映射本身内部配置了.ignore(p =&gt; p.Name),问题就消失了

public void Configure(EntityTypeBuilder<User> builder)
{
    builder.HasKey(x => x.UserId);

    builder.Property(x => x.Name)
        .HasMaxLength(200);

    builder.Property(x => x.DocumentNumber)
        .HasMaxLength(50);

    builder.OwnsOne(x => x.Profile, profile =>
    {
        profile.Property(c => c.Value)
        .IsRequired()
        .HasColumnName("ProfileId")
        .HasColumnType("integer");

        profile.Ignore(p => p.Name);
    });
 }

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2018-11-02
    • 2017-02-26
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    相关资源
    最近更新 更多