Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 753
Nimish David Mathew Avatar asked Nov 01 '19 12:11

Nimish David Mathew


2 Answers

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).

like image 90
Nimish David Mathew Avatar answered Sep 27 '22 19:09

Nimish David Mathew


Use [ForeignKey("GenderId")] on your public virtual Gender Gender { get; set; } property . Thus GenderId would be identified as a foreign key for Associated User.

See below updated code:

public class User
{
    public int GenderId { get; set; }
    [ForeignKey("Id")]//Gender Primary key
    public virtual Gender Gender { get; set; }
}

Hope it will fix your issue.

Thanks,

like image 35
Sunil Kumar Avatar answered Sep 27 '22 21:09

Sunil Kumar