entity framework - Linq: adding conditions to the where clause conditionally -
i have query this
(from u in datacontext.users u.division == struserdiv && u.age > 18 && u.height > strheightinfeet select new dto_usermaster { prop1 = u.name, }).tolist(); i want add various conditions age, height based on whether conditions provided method running query. conditions include user division. if age supplied want add query. similary, if height provided want add well.
if done using sql queries have used string builder have them appended main strsql query. here in linq can think of using if condition write same query thrice, each if block having additional condition. there better way this?
thanks time..
if not call tolist() , final mapping dto type, can add where clauses go, , build results @ end:
var query = u in datacontext.users u.division == struserdiv && u.age > 18 && u.height > strheightinfeet select u; if (useage) query = query.where(u => u.age > age); if (useheight) query = query.where(u => u.height > strheightinfeet); // build results @ end var results = query.select(u => new dto_usermaster { prop1 = u.name, }).tolist(); this still result in single call database, efficient writing query in 1 pass.
Comments
Post a Comment