Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
I have two classes, Contestant and Picture, with the following setup: public class Contestant { ... public int AvatarID { get; set; } [ForeignKey(nameof(AvatarID))] public ...
#2: Post edited
How to refer to the same table twice from one Entity Framework entity?
- How to refer to the same class twice from one Entity Framework entity?
#1: Initial revision
How to refer to the same table twice from one Entity Framework entity?
I have two classes, Contestant and Picture, with the following setup: public class Contestant { ... public int AvatarID { get; set; } [ForeignKey(nameof(AvatarID))] public virtual Picture? Avatar { get; set; } public virtual ICollection<Picture>? Pictures { get; set; } ... } public class Picture { ... public int ContestantID { get; set; } [ForeignKey(nameof(ContestantID))] public virtual Contestant? Contestant { get; set; } ... } Each contestant instance has a set of pictures and a single picture from the set that serves as their avatar. The original setup (without AvatarID or Avatar relationship) worked fine. After adding the Avatar field and relationship, I get a run-time error message when I try to load either the Contestant set or Picture set. It reads: > System.InvalidOperationException: 'Unable to determine the relationship represented by navigation 'Contestant.Avatar' of type 'Picture.' Either manually configure the relationship, or ignore this property using the '[NotMapper]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.' From my research, this happens when a class refers to another class twice. The answers I saw all involved the same class having both keys of the relationship. For example, a Project class might have multiple employees assigned, one as ProjectEngineer the other as AssignedDeveloper. For those, defining the [ForeignKey()] in the same file worked. I do not know what I need to do, here or possibly in the DbContext's OnModelCreating method.