我正在为一个应用程序添加聊天功能,所以当用户登录时,我需要将它们全部发送到“看不见”的状态。消息,我正在使用entityframework,我喜欢只返回最近20条看不见的消息。但是我的查询无效,目前我得到了这个例外
计数必须是DbConstantExpression或DbParameterReferenceExpression
我做错了什么?
List<ChatVM> unSeenChats = db.Chats.Where(chat => !chat.Seen)
.Select(chat => new ChatVM
{
Id = chat.Id,
IsAnnonymous = chat.IsAnnonymous,
UserName = chat.UserName,
Messages = chat.Messages
.OrderBy(x => x.DateTime)
.Skip(chat.Messages.Count - 20 > 0
? chat.Messages.Count - 20
: 0)
.Take(20)
.Select(message => new MessageVM
{
Id = message.Id,
DateTime = message.DateTime,
Text = message.Text
}).ToList()
}).ToList();
我的模型如下:
public class Chat
{
...
public virtual ICollection<Message> Messages { get; set; }
}
public class Message
{
...
public int ChatId { get; set; }
public virtual Chat Chat { get; set; }
}
public class Entities : IdentityDbContext<ApplicationUser>
{
....
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
...
modelBuilder.Entity<Message>()
.HasRequired(p => p.Chat).WithMany(p => p.Messages).WillCascadeOnDelete(true);
}
}
感谢
答案 0 :(得分:2)
我认为您不允许在查询中使用.Count
(因此您看到的错误)。无论如何,我认为你从错误的角度看待这个问题。你可能应该使用OrderByDescending
方法,然后从那里抓住前20个帖子。
这样的事情:
List<ChatVM> unSeenChats = db.Chats.Where(chat => !chat.Seen)
.Select(chat => new ChatVM
{
Id = chat.Id,
IsAnnonymous = chat.IsAnnonymous,
UserName = chat.UserName,
Messages = chat.Messages
.OrderByDescending(x => x.DateTime)
.Take(20)
.Select(message => new MessageVM
{
Id = message.Id,
DateTime = message.DateTime,
Text = message.Text
}).ToList()
}).ToList();