c# - How to query from the table using group by with EF6? -
i have table below , need query groups roleid values list , put dto. example , expected result below table.
i know should not complex stuff can't figure out how... went through few examples , have found examples deal count of grouped stuff , not list of them.
+----+--------+--------+ | id | userid | roleid | +----+--------+--------+ | 1 | 1 | 1 | +----+--------+--------+ | 2 | 1 | 2 | +----+--------+--------+ | 3 | 2 | 1 | +----+--------+--------+ public class userroledto { public int userid { get; set; } public list<int> roleids { get; set; } } expected result:
var res = new list<userroledto> { new userroledto() { userid = 1, roleids = new list<int>() {1, 2} }, new userroledto() { userid = 2, roleids = new list<int>() {1} } };
supposing have mapped junction table entity on model, this:
using(var db=new yourcontext()) { var res= db.userroles.groupby(ur=>ur.userid) .select(g=>new userroledto() { userid = g.key, roleids = g.select(us=>us.roleid).tolist() } ).tolist(); }
Comments
Post a Comment