EF problems with navigation and display properties
In the beginning I wanted to mention that I have been struggling with this thing for several days and have tried to answer many of the answers more or less related to this issue. But I couldn't solve it.
I have two classes that represent tables in a DB. These are the existing tables used by the old application and I cannot change them.
A message can contain multiple MessageRecipients.
Environment: MVC3, EF4.1
Classes:
public class Message
{
[ForeignKey("MessageReciepients")]
public virtual int MessageID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Recieved { get; set; }
[ForeignKey("User")]
public int AuthorUserID { get; set; }
//P\\ Navigation properties
public virtual IList<MessageRecipient> MessageReciepients { get; set; }
public virtual User User { get; set; }
}
public class MessageRecipient
{
//[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int MessageID { get; set; }
public int UserID { get; set; }
public bool Read { get; set; }
public bool Important { get; set; }
public bool Deleted { get; set; }
public bool Destroyed { get; set; }
//P\\ Navigation Properties
public virtual User User { get; set; }
}
I have an error:
Foreign Key Component 'MessageID' is not a declared property in type "MessageRecipient". Make sure that it has not been explicitly excluded from the model and that it is a valid primitive property.
How do I correctly map these classes, relationships to load message recipients?
I can add that the navigation property User is working correctly for the post and is loading user data correctly.
I am not too experienced with .NET and I find out when I do this. I tried the EF API config to map these I tried to swear it, curse it and be close to crying and praying at the same time. No joy!
I am very grateful for the help.
source to share
It turned out that the problem was related to the composite key that I need to use, and this can all be solved with some attributes:
This is how it looks now:
public class Message
{
public int MessageID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Recieved { get; set; }
[ForeignKey("User")]
public int AuthorUserID { get; set; }
//P\\ Navigation properties
public virtual ICollection<MessageRecipient> MessageRecipients { get; set; }
public virtual User User { get; set; }
}
public class MessageRecipient
{
[Key, Column(Order=0), ForeignKey("User")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int UserID { get; set; }
[Key, Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int MessageID { get; set; }
public bool Read { get; set; }
public bool Important { get; set; }
public bool Deleted { get; set; }
public bool Destroyed { get; set; }
//P\\ Navigation Properties
public virtual User User { get; set; }
}
source to share