Mapping attribute to specify that a navigation property is unidirectional.
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.4k
- PR merge metrics
- PR metrics pending
Description
When defining bi-directional relationships we can use InverseProperty to hint EF what to use on the other end. However, I have run into a case where I had an existing one-way relationship (HasOne.WithMany()) to a table, where I added a new Many-to-Many relationship to the same table. I use attributes by default for basic mapping expressions and explicit config only as needed.
In this case I have a base class for editable entites that defines references to a User for CreatedBy and LastModifiedBy. These do not have inverse properties from User back to anything.
I had another entity called Role where I also have a many-to-many between Users and Roles. I explicitly mapped this relationship as:
builder.HasMany(x => x.Roles)
.WithMany(x => x.Users)
.UsingEntity("UserRoles",
l => l.HasOne(typeof(Role)).WithMany().HasForeignKey("RoleId"),
r => r.HasOne(typeof(User)).WithMany().HasForeignKey("UserId"),
j => j.HasKey("UserId", "RoleId"));
However, after introducing a Roles collection on User, and a Users collection or Role to serve this relationship mapping, I received the following new error:
Unable to determine the relationship represented by navigation 'Role.CreatedBy' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'
Without explictly configuring Role.HasOne(x => x.CreatedBy)/WithMany() in the role configuration (and the LastModifiedBy as well) it appears that the relationship is looking to use User.Roles on the other end.
What I would like to suggest, if this isn't actually a bug, is to support something like a NoInverseProperty attribute to indicate that the mapping should treat the relationship as a WithMany() rather than trying to resolve a relationship on the other side.
Contributor guide
Assessment
This issue has not been assessed yet.