Trying to do a .Distinct() clause in ASP.net MVC Entity Framework, but getting an error on the following code:
var tblGlobalLogOnLogOffStudentBans = db.tblGlobalLogOnLogOffStudentBans.Include(t => t.tblGlobalLogOnLogOffTime).OrderBy(t => t.StartBan).Take(10).Select(t => t.UserID).Distinct();
The error is:
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
is an Int, but is shown on the page as a Username + First & Last Name. Any ideas?
Thanks Chris
You're selecting the user ID (resulting in a sequence of user IDs) and then calling Distinct
on that. The result is still a sequence of user IDs... whereas it looks like your page wants a sequence of tblGlobalLogOnLogOffStudentBan
. I suspect you want to keep the whole entity, but just make them distinct by user ID. That's most easily done with grouping:
var tblGlobalLogOnLogOffStudentBans = db.tblGlobalLogOnLogOffStudentBans
.Include(t => t.tblGlobalLogOnLogOffTime)
.OrderBy(t => t.StartBan)
.GroupBy(t => t.UserID)
.Select(g => g.First())
.Take(10);
Note that I've moved the grouping to before the Take(10)
, with the assumption that you want the first 10 users rather than the first 10 bans then grouped by user. (Are you sure you don't want OrderByDescending
in order to show the most recent bans?)
See more on this question at Stackoverflow