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.
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)
.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With