General function for retrieving data using entity structures

I am trying to create a generic function to retrieve data from a database using Entity Framework. I pass id as the key to retrieve. For this, 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 works without problems. But how can I change this function to receive data if I do not pass the primary key as a filter?

+5
source share
1 answer

You can pass the 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"); 
+10
source

Source: https://habr.com/ru/post/1232164/


All Articles