entity framework - EF: OrderBy is not working when I define a delegate with the same signature -
i've replaced sqldatasource objectdatasource. here's portion of select method
func<user, string> sortbydlg = (u) => { string sortstr = string.isnullorempty(sortcolumn) ? "username" : sortcolumn; return sortstr; }; var users = db.users.orderby(sortbydlg).tolist();
the first time page loads, want rows sorted username, after column selected.
when run code, no sorting happening. works when put anonymous method: orderby(u => u.username)
.
here's complete method
public static list<userviewmodel> getalluserviewmodels(string sortcolumn) { using (var db = mydbcontext.create()) { var model = new list<userviewmodel>(); func<user, string> sortbydlg = (u) => { string sortstr = string.isnullorempty(sortcolumn) ? "username" : sortcolumn; return sortstr; }; var users = db.users.orderby(sortbydlg).tolist(); foreach (var item in users) { var u = new userviewmodel { userid = item.id, first_name = item.firstname, last_name = item.lastname, telephone = item.telephone, //more here ... }; model.add(u); } return model; } }
thanks helping
this how it, because find simple understand (without using expression trees):
public static list<userviewmodel> getalluserviewmodels(string sortcolumn) { using (var db = mydbcontext.create()) { var query = db.users.asqueryable(); switch(string.isnullorempty(sortcolumn) ? "username" : sortcolumn) { case "username": query=query.orderby(u=>u.username); break; case "firstname": query=query.orderby(u=>u.firstname); break; ... more ... } var model = query.select(u=> new userviewmodel { userid = item.id, first_name = item.firstname, last_name = item.lastname, telephone = item.telephone, //more here ... }).tolist(); return model; } }
actually, create functions getallusers returns iqueryable<user>
, separate extension method iqueryable<user> orderbycolumn(this iqueryable<user> u,string sortcolumn)
, , extension ienumerable<userviewmodelitem> toviewmodel(this iqueryable<user> u)
, , use them like: var result = getallusers().orderbycolumn("username").toviewmodel();
// db defined elsewhere (repository pattern?) public iqueryable<user> getallusers() { return db.users.asqueryable(); } public static iqueryable<user> orderbycolumn(this iqueryable<user> u,string sortcolumn) { switch(string.isnullorempty(sortcolumn) ? "username" : sortcolumn) { case "username": return u.orderby(u=>u.username); break; case "firstname": return u.orderby(u=>u.firstname); break; ... more ... } } public static ienumerable<userviewmodelitem> toviewmodel(this iqueryable<user> users) { return users.select(u=> new userviewmodelitem { userid = item.id, first_name = item.firstname, last_name = item.lastname, telephone = item.telephone, //more here ... }).tolist(); }
Comments
Post a Comment