Search code examples
c#ef-code-firstentityef-core-2.2ef-core-3.1

.Ignore() throwing exception after migration to EFCore 3.1


I had this block of code working before migrate to EFcore 3.1 (using 2.2 before the migration) and now its throwing the following exeception: '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);
}

The scenario is: The ProfileEnum is a complex type that I map to User class using the following block

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;
    }
}

Solution

  • I ended up configuring the .ignore(p => p.Name) inside the entity mapping itself and the problem is gone

    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);
        });
     }