c# - Distinct 子句导致类型错误

标签 c# asp.net asp.net-mvc entity-framework

尝试在 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/

相关文章:

asp.net - 如何为设计人员提供 ASP .NET 母版页的轻松编辑?

c# - 如何搜索多维数组?

c# - 引用的项目和配置文件

c# - 在嵌套 ListView 中访问父数据项

c# - ASP.NET MVC,错误输出源代码

asp.net-mvc - MVC @Url.Abs 助手似乎不存在

c# - 模型将集合属性与局部 View 绑定(bind)

asp.net-mvc - Windows Azure 服务总线通知中心仅接收部分通知

c# - 什么是 DateRange 类的好 hashCode

c# - 自定义 BotState 存储 - 删除旧的状态数据条目