'propertyName' cannot be used as a property on entity type 'typeName' because it is configured as a navigation
Solution 1
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)
.
Solution 2
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,
Solution 3
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)
Solution 4
I had the same problem for a complex hierarchy model with nested complex classes in it.
Apparently, the IsRequired()
method conflicts with OnDelete(...)
. I removed the IsRequired()
and everything got back to normal.
public class MyComplexClassConfig : IEntityTypeConfiguration<MyComplexClass>
{
public void Configure(EntityTypeBuilder<MyComplexClass> builder)
{
builder
.HasOne(col => col.ChildClass)
.WithOne(col => col.ParentClass)
.OnDelete(DeleteBehavior.Cascade);
// The following line of code needs to be deleted.
builder.Property(col => col.Customer).IsRequired();
}
}
Related videos on Youtube
Nimish David Mathew
Updated on September 15, 2022Comments
-
Nimish David Mathew over 1 year
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.
-
Ivan Stoev over 4 yearsThe error cannot be from the shown model and configuration. There must be something else in your real code, like
.Property(x => x.Gender)
or similar. -
Nimish David Mathew over 4 yearsI'm sorry. I missed to add one bit of code to the question which actually caused the problem.
user.HasIndex(x => x.Gender);
I was trying to create an index on a navigation property. I had to change this touser.HasIndex(x => x.GenderId);
-
-
Nimish David Mathew over 4 yearsDoesn't
.HasForeignKey(x => x.GenderId);
insideDbContext
do the same thing?