Optimus
Optimus

Reputation: 2210

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?

Upvotes: 8

Views: 5986

Answers (1)

David L
David L

Reputation: 33833

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");

Upvotes: 19

Related Questions