I’m trying to use Entity Framework for the first time, and have come a bit unstuck.
I have a class AccountDataAccess:
public class AccountDataAccess
{
public IEnumerable<Account> Get(Account account)
{
}
}
And another class, Account
public class Account
{
string UserName { get; set; }
string Password { get; set; }
string Email { get; set; }
Session Session { get; set; }
}
When AccountDataAccess.Get() is called, one or more of the account parameters’ fields could be populated (e.g. only UserName has a value).
Is there a way in Entity Framework to query the database with the search containing only the fields that contain values?
After doing some googling, the only way I can see doing it is something like
public IEnumerable<Account> Get(Account account)
{
StringBuilder queryStringBuilder = new StringBuilder("SELECT VALUE account FROM MyDatabase.Account as account WHERE ");
if (!String.IsNullOrWhiteSpace(account.UserName))
queryStringBuilder.Append("UserName = " + account.UserName);
if (!String.IsNullOrWhiteSpace(account.Email))
queryStringBuilder.Append("Email = " + account.Email);
...
//continue for all fields
//then call database
}
Obviously this is a terrible way of doing it though. Any ideas?
EDIT
So for a full example, if I had
Account account1 = new Account() {UserName = "UserA", Email = "UserA@email.com"};
Account account2 = new Account() {UserName = "UserB"};
I would expect the query for account1 to be
var _context = new EntityModel();
return _context.Where(w => w.UserName == account.UserName
&& w.UserName == account1.UserName
&& w.Email == account1.Email
).ToList();
But the query for account2 to ignore the email field as it isn’t populated:
var _context = new EntityModel();
return _context.Where(w => w.UserName == account2.UserName
).ToList();
So I guess my question is can I dynamically generate that Where lambda expression to only include fields that have values?
The query isn’t processed until you add an evaluative operation like ToList(). So one thing you can do is build out your query similar to the way you would in SQL.
You could also do the same with query syntax, though it’s a bit more verbose.
When you have finished building out your query, run ToList(), ToArray(), etc. on it to actually execute it and read from the database.