说有一个类似于以下的实体结构:
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
,因为所有这些都存在于许多“会话”列表中。
谢谢!
答案 0 :(得分:1)
通常,您在会话实体上不会有LastMessage,而仅根据需要查询它。像这样:
var q = from c in db.Conversations
select new {Conversation=c, LastMessage = c.Messages.OrderByDescending(m => m.Id).Take(1)};