c# - Querying Entity Framework with an object -
i'm trying use entity framework first time, , have come bit unstuck.
i have class accountdataaccess:
public class accountdataaccess { public ienumerable<account> get(account account) { } }
and class, account
public class account { string username { get; set; } string password { get; set; } string email { get; set; } session session { get; set; } }
when accountdataaccess.get() called, 1 or more of account parameters' fields populated (e.g. username has value). there way in entity framework query database search containing fields contain values?
after doing googling, way can see doing like
public ienumerable<account> get(account account) { stringbuilder querystringbuilder = new stringbuilder("select value account mydatabase.account account "); if (!string.isnullorwhitespace(account.username)) querystringbuilder.append("username = " + account.username); if (!string.isnullorwhitespace(account.email)) querystringbuilder.append("email = " + account.email); ... //continue fields //then call database }
obviously terrible way of doing though. ideas?
edit
so full example, if had
account account1 = new account() {username = "usera", email = "usera@email.com"}; account account2 = new account() {username = "userb"};
i expect query account1 be
var _context = new entitymodel(); return _context.where(w => w.username == account.username && w.username == account1.username && w.email == account1.email ).tolist();
but query account2 ignore email field isn't populated:
var _context = new entitymodel(); return _context.where(w => w.username == account2.username ).tolist();
so guess question can dynamically generate lambda expression include fields have values?
the query isn't processed until add evaluative operation tolist(). 1 thing can build out query similar way in sql.
var query = _context.accounts.asqueryable(); if (!string.isnullorwhitespace(account1.username)) query = query.where(a => a.username == account1.username); if (!string.isnullorwhitespace(account1.email)) query = query.where(a => a.email == account1.email);
you same query syntax, though it's bit more verbose.
when have finished building out query, run tolist(), toarray(), etc. on execute , read database.
Comments
Post a Comment