Reputation: 81
In my application (Winforms), there is 'Search' form. And I have 9 fields (such as name, surname, city etc.) I need, if 4 fields are filled, I will search by 4 fields.
For example: user entered; Name, Surname, City
Application will search by those fields.
With SqlConnection
, I am using parameters.Add
method. But with Entity Framework, I don't know how can I use it.
Sorry for my english :)
Thanks
Upvotes: 0
Views: 416
Reputation: 38608
You could check in your method if the parameters is empty and if not, add the parameter as a condition using the Where
method. You just execute the query when you call a method to concrete it in a type, for sample: FirstOrDefault
, ToList()
, so you can prepare you query adding the parameters. You could try something like this:
// create the query type (IQueryable, DbSet, etc...)
IQueryable<Entity> query = context.Entity;
// check the parameters and add using the Where method
if (!string.IsNullOrEmpty(userName))
query = query.Where(x => x.UserName.Constains(userName));
if (!string.IsNullOrEmpty(surName))
query = query.Where(x => x.SurName.Constains(surName));
if (!string.IsNullOrEmpty(city))
query = query.Where(x => x.City == city);
// execute the query and get results...
var result = query.ToList();
Upvotes: 3