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"));
The Linq Where method takes a parameter of Func<T, bool>
where T would be the dbSet object type you want to apply your Where method on.
So to make your code work, you can do this:
public MyObjectCollection(Func<T, bool> 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);
}
}
}
UPDATE: Also, to achieve the functionality you are looking for with a generic collection, instead of encapsulating a private List object, you could inherit from List like I show below. So, if you wanted MyObjectCollection
to function like a List, you can do something like I show below.
So with your code from above, you can change to this:
public class MyObjectCollection<T> : List<T> where T : class
{
public MyObjectCollection()
{
using (var db = new MyContext())
{
foreach (T row in db.Set<T>())
{
// Enumerate the data, do whatever with it...
this.Add(row);
}
}
}
public MyObjectCollection(Func<T, bool> MyLinqExpression)
{
using (var db = new MyContext())
{
foreach (T row in db.Set<T>().Where(MyLinqExpression))
{
// Enumerate the data, do whatever with it...
this.Add(row);
}
}
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加