简体   繁体   中英

How to create a relation between 3 entities in EF Core?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM