I'm trying to create a generic function to get data from DB using Entity Framework. I'm passing an id
as key for the retrieval. To do that I wrote the following function
public T Get<T>(object id) where T : class
{
T item = null;
using (var context = MyContext())
{
item = context.Set<T>().Find(id);
}
return item;
}
The function is working without any problem. But how can I modify this function to get data if I'm not passing the primary key as filter?
You can pass a predicate expression and use .FirstOrDefault()
.
public T Get<T>(Expression<Func<T, bool>> predicate)
where T : class
{
T item = null;
using (var context = MyContext())
{
item = context.Set<T>().FirstOrDefault(predicate);
}
return item;
}
var customer = context.Get<Customer>(x => x.Name == "Bob");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With