'propertyName' cannot be used as a property on entity type 'typeName' because it is configured as a navigation

asp.net asp.net-core c# entity-framework entity-framework-core

Question

I have an entity user with the following:

public class User
{
    [Key, Required]
    public int Id { get; set; }
    public int GenderId { get; set; }
    public virtual Gender Gender { get; set; }
}

In gender:

public class Gender
{
    [Key, Required]
    public int Id { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

Then, inside my DbContext, I have:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>(user =>
    {
        user
        .HasOne(x => x.Gender)
        .WithMany(x => x.Users)
        .HasForeignKey(x => x.GenderId);
    }

    user.HasIndex(x => x.Gender);
}

When I run dotnet ef add migration User, I am getting the error:

'Gender' cannot be used as a property on entity type 'User' because it is configured as a navigation.

1
1
11/1/2019 1:45:58 PM

Accepted Answer

I was trying to create an index on a navigation property. Instead, create the index on the foreign key.

Change user.HasIndex(x => x.Gender) to user.HasIndex(x => x.GenderId).

1
12/18/2019 12:56:50 PM

Popular Answer

I had a similar error:

'Product' cannot be used as a property on entity type 'OrderLine' because it is configured as a navigation.

The cause of the error was that in the fluent api I also used the entity as a property:

modelBuilder.Entity<OrderLine>().Property(ol => ol.Product).IsRequired(true)


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow