I want to build a chat application with EF Core which consists of 3 entities: user, chat & message
.
Each user should contain a list of all chats he is in. Each chat should contain the two users who are in the chat and all messages, sent in the chat. Each message should contain the chat, the message is sent in and the user who sent the message.
Those are my current entities:
public class User
{
public string Id { get; set; }
public string Name { get; set; }
public List<Chat> Chats { get; set; }
}
public class Chat
{
public string Id { get; set; }
public User User1 { get; set; }
public User User2 { get; set; }
public List<Message> Messages { get; set; }
}
public class Message
{
public string Id { get; set; }
public string Text { get; set; }
public User Sender { get; set; }
public Chat Chat { get; set; }
}
I tried many things but nothing worked.
CodePudding user response:
Change your model to
public class Chat
{
public string Id { get; set; }
public List<User> Users{ get; set; }
public List<Message> Messages { get; set; }
}
And you've got a simple Many-to-Many relationship.
CodePudding user response:
Hello This is the right way to make your relationships whit EF Core.
public class User
{
public User()
{
this.Chats = new HashSet<Chat>();
}
public string Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Chat> Chats { get; set; }
}
public class Chat
{
public Chat()
{
this.Users = new HashSet<User>();
this.Messages = new HashSet<Message>();
}
public string Id { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<Message> Messages { get; set; }
}
public class Message
{
public string Id { get; set; }
public string Text { get; set; }
public string ChatId { get; set; }
public Chat Chat { get; set; }
}
Уou can access the Users through your Users collection in Chat. Also you can access Chats of current user through Chats property in User