I have an Entity Framework class set up to read a table from a SQL database, but I can't quite figure out how to pass a LINQ expression to filter only certain objects. I know there is a way to build an expression tree and do this dynamically from within the class, but I can't seem to figure the best way to do this.
Any tips are appreciated.
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
class MyObjectCollection<T> where T : class
{
private List<T> myInternalCollection = new List<T>();
MyObjectCollection()
{
using (var db = new MyContext())
{
foreach (T row in db.Set<T>())
{
// Enumerate the data, do whatever with it...
myInternalCollection.Add(row);
}
}
}
MyObjectCollection(var MyLinqExpression)
{
using (var db = new MyContext())
{
foreach (T row in db.Set<T>().Where.MyLinqExpression()
{
// Enumerate the data, do whatever with it...
myInternalCollection.Add(row);
}
}
}
}
// Works fine:
MyObjectCollection<Customer> allCustomers = new MyObjectCollection<Customer>();
// Would like something like this:
MyObjectCollection<Customer> customersP = new MyObjectCollection<Customer>(c => c.StartsWith("P"));