Answer the question
In order to leave comments, you need to log in
How to set up relationships between tables in EntityFramework that refer to each other by foreign key?
Hello!
There are two tables in the database for which two classes are created in the code:
public class ForumTopic
{
[Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int TopicId { get; set; }
public int LastMessageId { get; set; }
[ForeignKey("LastMessageId")]
public virtual ForumMessage LastMessage { get; set; }
}
public class ForumMessage
{
[Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int MessageID { get; set; }
public int TopicID { get; set; }
[ForeignKey("TopicID")]
public virtual ForumTopic Topic { get; set; }
}
Answer the question
In order to leave comments, you need to log in
Thanks Fat Lorrie for the tip.
Indeed, without specifying a reference to the collection of records in the child table in the form of such a property:
public virtual ICollection Messages { get; set; }
EF couldn't figure out what relationship these two tables had.
but this was not enough, because. there was still an ambiguity that I managed to resolve using the InversePropertyAttribute attribute, which I added before this very property.
As a result, the class structure became like this:
public class ForumTopic
{
[Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int TopicId { get; set; }
public int LastMessageId { get; set; }
[ForeignKey("LastMessageId")]
public virtual ForumMessage LastMessage { get; set; }
[InverseProperty("Topic")]
public virtual ICollection<ForumMessage> Messages { get; set; }
}
public class ForumMessage
{
[Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int MessageID { get; set; }
public int TopicID { get; set; }
[ForeignKey("TopicID")]
public virtual ForumTopic Topic { get; set; }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question