EF Core-在列表查询结果中包含会话中的最新消息

时间:2018-07-07 02:52:36

标签: sql-server entity-framework tsql .net-core

说有一个类似于以下的实体结构:

class Conversation
{
    [Key]
    public long Id { get; set; }

    public long CreatorId { get; set; }

    public long RecipientId { get; set; }

    public IQueryable<Message> Messages { get; set; }

    // Populate this with the most recent sent/received message:

    public Message LastMessage { get; set; }
}

class Message
{
    [Key]
    public long Id { get; set; } 

    public long SenderId { get; set; }

    public string Body { get; set; }

    [ForeignKey("Conversation")]
    public long ConversationId { get; set; }

    public Conversation Conversation { get; set; }
}

是否可以使用该对话的最新消息来填充LastMessage?将使用Message外键将Conversation映射到其ConversationId


如果这不可能,那么像这样的对话实体是否有可能?

class Conversation
{
    [Key]
    public long Id { get; set; }

    public long CreatorId { get; set; }

    public long RecipientId { get; set; }

    [ForeignKey("ConversationId")]
    public IQueryable<Message> Messages { get; set; }

    // Populate these fields with the respective values from the most recent message:

    public long LastMessageSenderId { get; set; }

    public string LastMessageBody { get; set; }
}

这里最主要的是将所有这些结果包含在单个SELECT查询中,并且在检索初始结果后不必访问Messages,因为所有这些都存在于许多“会话”列表中。

谢谢!

1 个答案:

答案 0 :(得分:1)

通常,您在会话实体上不会有LastMessage,而仅根据需要查询它。像这样:

var q = from c in db.Conversations 
        select new {Conversation=c, LastMessage = c.Messages.OrderByDescending(m => m.Id).Take(1)};