Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic function for getting data using entity framework

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?

like image 893
Optimus Avatar asked Sep 24 '15 04:09

Optimus


1 Answers

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");
like image 123
David L Avatar answered Nov 14 '22 22:11

David L