I need to create two tables through CodeFirst in Entity with a 1 to many link. The bottom line is that there is a user who may have multiple messages. And in some cases, you need to display all messages of a specific user. For this, I need to make two classes of entities, but I can’t understand how to do this correctly. Here is my option:

public class User { public int Id { get; set; } public int? MessagesId { get; set; } public string Name { get; set; } public Messages UserMessages { get; set; } } public class Messages { public int Id { get; set; } public DateTime Date { get; set; } public ICollection<string> UserMessages { get; set; } public Messages() { UserMessages = new List<string>(); } } 

But I feel that there is something wrong. I can not understand what exactly. Tell me who knows.

    1 answer 1

    You need to keep the user links to all his posts. And messages to store links to the user who created them.

    The code will look like this

     public class User { public int Id { get; set; } public string Name { get; set; } //ссылка на сообщения public virtual ICollection<Message> Messages { get; set; } public User() { Messages = new List<Message>(); } } public class Message { public int Id { get; set; } public DateTime Date { get; set; } public string Text {get; set; } //ссылка на пользователя public int UserId { get; set; } public virtual User User { get; set; } } 

    UserId - does not accept null , because a message can only be created if there is a user.