Reputation: 2129
In Entity Framework Core (v5.0.6) I'm trying to create a relationship where the object has both a foreign key id field AND a navigation property both of which have non-standard names but when I try to build a migration, I'm getting an error saying Unable to determine the relationship represented by navigation 'Org.IntegrationAdmin' of type 'OrgUser'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'
My code is:
public class OrgUser
{
public Guid Id { get; set; }
public string Name { get; set; }
public Guid OrgId { get; set; }
public virtual Org? Org { get; set; }
}
public class Org
{
[ForeignKey(nameof(OrgUser))]
public Guid IntegrationAdminId { get; set; }
[ForeignKey(nameof(IntegrationAdminId))]
public virtual OrgUser? IntegrationAdmin { get; set; }
}
The reason for the non-standard names is that the Org class will actually have several foreign key / navigation properties in it so using standard naming is not an option.
I would rather do this with attributes rather than fluent syntax.
I want to have both the id and the navigation property as sometimes will want to include the navigation property but others, just want the id, which will be useful for comparing records without the overhead of doing a db join.
Update: Sorry for wasting peoples time but I made the classic mistake of inadvertently editing out the important part of my code 🤦♂️🤦♂️🤦♂️ I've added the reference to Org into OrgUser that was confusing EF!
Upvotes: 1
Views: 4457
Reputation: 2129
I've found the problem, it was that in addition to the OrgUser ref in Org, there was also an Org ref in OrgUser that I'd not noticed.
This confused EF and resulted in an error message that pointed at the wrong thing and confused the hell out of me.
I removed all ForeignKey
attributes and then added the following to my DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Org>(entity =>
{
entity.HasOne(o => o.IntegrationAdmin)
.WithMany();
});
modelBuilder.Entity<OrgUser>(entity =>
{
entity.HasOne(d => d.Org)
.WithMany();
});
}
Upvotes: -1
Reputation: 43931
Try this
public class OrgUser
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
[InverseProperty(nameof(Org.IntegrationAdmin))]
public virtual ICollection<Org> Orgs { get; set; }
}
public class Org
{
[Key]
public Guid Id { get; set; }
public Guid? IntegrationAdminId { get; set; }
[ForeignKey(nameof(IntegrationAdminId))]
[InverseProperty("Orgs")]
public virtual OrgUser IntegrationAdmin { get; set; }
}
or you can try dbcontext
modelBuilder.Entity<Org>(entity =>
{
entity.HasOne(d => d.IntegrationAdmin)
.WithMany(p => p.Orgs)
.HasForeignKey(d => d.IntegrationAdminId )
.OnDelete(DeleteBehavior.ClientSetNull);
});
Upvotes: 3