尝试在 ASP.net MVC Entity Framework 中执行 .Distinct() 子句,但在以下代码中出现错误:
var tblGlobalLogOnLogOffStudentBans = db.tblGlobalLogOnLogOffStudentBans.Include(t => t.tblGlobalLogOnLogOffTime).OrderBy(t => t.StartBan).Take(10).Select(t => t.UserID).Distinct();
错误是:
Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.Nullable`1[System.Int32]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Dashboard.tblGlobalLogOnLogOffStudentBan]'.
t => t.UserID
是一个 Int,但在页面上显示为用户名 + 名字和姓氏。有什么想法吗?
谢谢 克里斯
最佳答案
您要选择用户 ID(产生一系列用户 ID),然后对其调用 Distinct
。结果仍然是用户 ID 序列……而您的页面看起来需要一系列 tblGlobalLogOnLogOffStudentBan
。我怀疑您想要保留整个实体,但只是通过 用户 ID 使它们不同。这通过分组最容易完成:
var tblGlobalLogOnLogOffStudentBans = db.tblGlobalLogOnLogOffStudentBans
.Include(t => t.tblGlobalLogOnLogOffTime)
.OrderBy(t => t.StartBan)
.GroupBy(t => t.UserID)
.Select(g => g.First())
.Take(10);
请注意,我已将分组移动到Take(10)
之前,假设您想要前 10 个用户而不是前 10 个禁令 < em>then 按用户分组。 (您确定不希望OrderByDescending
来显示最近的 禁令吗?)
关于c# - Distinct 子句导致类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29671664/