【问题标题】:nested includes in .net core 1.1.net core 1.1 中的嵌套包含
【发布时间】:2017-10-20 20:41:52
【问题描述】:

我在 .net core 1.1 MVC 中有三个模型。

  1. 通讯

    public class Communication
    {
        public Guid CommunicationId { get; set; }
        public string Subject { get; set; }
        public bool IsRead { get; set; } = false;
        public Guid UserId { get; set; }
        public Guid AssignedTo { get; set; }
        public DateTime CreatedAt { get; set; } = DateTime.Now;
        public DateTime UpdatedAt { get; set; } = DateTime.Now;
        public Nullable<DateTime> DeletedAt { get; set; }
        public virtual ICollection<Message> Messages {get; set;}
    }
    
  2. 消息

    public class Message
    {
        public Guid MessageId { get; set; }
        public Guid CommunicationId { get; set; }
        public Guid SenderId { get; set; } = new Guid();
        public Guid ReceiverId { get; set; } = new Guid();
        public string Body { get; set; }
        public DateTime CreatedAt { get; set; } = DateTime.Now;
        public DateTime UpdatedAt { get; set; } = DateTime.Now;
        public Nullable<DateTime> DeletedAt { get; set; }
    }
    
  3. 用户

Messages 表中的SenderID 和ReceiverID 是Users 表中的UserID。

这些模型之间的关系: 通讯 has_many 消息。 消息属于_通信 通过 SenderID 向用户发送消息 通过 ReceiverId 向用户发送消息 blongs_

这是我的控制器的样子:

_context.Communications.Include(c=> c.Messages)

我想生成一个这样的 JSON 对象: {communicationId: 'xxx', messages[{messageId: 'xxx', 发件人:{用户信息在这里},接收者:{用户信息在这里} }

如何将 User 对象包含到 Message 对象中?

感谢您的帮助。

【问题讨论】:

    标签: c# .net-core entity-framework-core


    【解决方案1】:

    向 Message 表添加两个 Users 类型的属性,并使用它们分别定义 SenderId 和 ReceiverId 与 Users 表的关系。

    public virtual Users Sender { get; set; }
    public virtual Users Receiver { get; set; }
    

    然后像这样更改您的查询

    _context.Communications.Include(c => c.Messages).Include("Message.Users");
    

    【讨论】:

    • 嗨,摩根。还有一个问题。如何找到给定用户的所有通信?例如我的消息有一个 senderId 和 ReceiverId。 var communication = await _context.Communications.Include(c => c.Messages) .Where(m => m.Messages.senderId == id || m.Messages.ReceiverId == id).ToListAsync();这不是正确的语法。它应该是什么?谢谢
    • 你为什么不用ThenInclude
    • 我相信 ThenInclude 不是我的问题的正确解决方案。消息是一个集合。我需要一种查询收集对象的方法
    • 嗨阿吉特。我不确定我是否理解最后一个问题。但是,我将尝试根据您在评论中发布的相同代码来回答。如果您有一个 userId,并且希望分别基于 SenderId 或 ReceiverId 获取所有通信,那么您编写的示例代码应该可以正常工作。你试过运行它吗?你有没有得到任何错误?让我知道,以便我可以提供帮助。注意:如果答案解决了您的第一个问题,请将其标记为正确答案。
    猜你喜欢
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2017-09-29
    • 2016-04-01
    • 2018-08-03
    相关资源
    最近更新 更多