M
M
manst2014-11-11 16:55:50
Entity Framework
manst, 2014-11-11 16:55:50

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;}
}

Tell me how to add navigation properties in classes so that you can do this:
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

2 answer(s)
M
manst, 2014-11-20
@manst

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;}
    }

E
eee, 2014-11-20
@eee

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 question

Ask a Question

731 491 924 answers to any question