Answer the question
In order to leave comments, you need to log in
How to make navigation properties?
Good afternoon.
There are two classes Message and UserProfile, if you discard the extra ones:
//комментариями отмечены поля, как я представлял себе это сделать, но так не работает
public class Message
{
public int Id {get;set;}
public string Text {get;set;}
public int CreatedById {get;set;}
public int UpdatedById {get;set;}
//public virtual UserProfile CreatedBy {get;set;}
//public virtual UserProfile UpdatedBy {get;set;}
}
public class UserProfile
{
public int Id {get;set;}
public string Name {get;set;}
//public virtual ICollection<Message> CreatedMessages {get;set;}
//public virtual ICollection<Message> UpdatedMessages {get;set;}
}
var createdByUserName = context.Message.CreatedBy.Name;
var updatedByUserName = context.Message.UpdatedBy.Name;
var createdMessage = context.UserProfile.CreatedMessage.ToList();
var updatedMessage = context.UserProfile.UpdatedMessage.ToList();
Answer the question
In order to leave comments, you need to log in
The problem was solved by adding the [InverseProperty] attribute.
In the end, everything looks like this:
public class Message
{
public int Id { get; set; }
public string Text { get; set; }
public int CreatedById { get; set; }
public int ? UpdatedById { get; set; }
[InverseProperty("CreatedMessages")]
[ForeignKey("CreatedById")]
public virtual UserProfile CreatedBy { get; set; }
[InverseProperty("UpdatedMessages")]
[ForeignKey("UpdatedById")]
public virtual UserProfile UpdatedBy {get;set;}
}
public class UserProfile
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Message> CreatedMessages {get;set;}
public virtual ICollection<Message> UpdatedMessages {get;set;}
}
Uncomment the virtual properties, they're all right.
You are not calling the navigation properties correctly. It should be like this:
// Сначала находим нужное нам сообщение
var message = context.Messages.Find(Id);
// Затем мы можем получить навигационные свойства этой записи
var createdByUserName = message.CreatedBy.Name;
var updatedByUserName = message.UpdatedBy.Name;
// Получить другие сообщения автора данного сообщения
var creatorMessages = message.CreatedBy.CreatedMessages.ToList();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question