简体   繁体   English

如何在 EF Core 中创建 3 个实体之间的关系?

[英]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 .我想用 EF Core 构建一个聊天应用程序,它由 3 个实体组成: 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将您的 model 更改为

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.您好,这是与 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您还可以通过 User 中的 Chats 属性访问当前用户的 Chats

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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