Predicate or Dynamic Linq that can return from different object sets?

c# dynamic-linq entity-framework linq predicate

Question

Let's say I have two Entity Sets in my Entity Framework backed project, Cars and Trucks. Both Car and Truck implement IDriveable

Is it possible to have either a Predicate or Dynamic Linq to return a specific IDriveable, without the calling function having to know which set it gets loaded from?

Every example I have seen of Dlinq has something like this:

db.Cars.Where("ID==123");

The "dynamic" part comes after we've already selected the Table/set. I'd need something like

db.SomeMethod("Cars.Where(ID==123)");

As for predicates, the examples I have seen so far are functions to act on a list, something like:

static bool greaterThanTwo(int arg)
{
    return arg > 2;
}

Which assumes we already have a reference to the desired set. I need some way to dynamically tell it which table to load the record from as well filter on the unique ID of the record.

1
3
10/30/2013 3:07:04 PM

Popular Answer

I'm not sure i completely understand the question, but it seems like you don't really need the query to be dynamic, just which dbset you're querying. if that is the case, and you are filtering by id, something like this might work:

var type = Assembly.GetCallingAssembly().GetTypes().Single(x => x.Name == "Car");
var method = db.GetType().GetMethod("Set", BindingFlags.Instance | BindingFlags.Public).MakeGenericMethod(type);
var set = (DbSet) method.Invoke(db, new object[0]);
var myDrivableThing = (IDrivable) set.Find(id);

this is entirely untested and may not compile, so take that with a grain of salt, but it should get you a dbset for whatever dynamic type you want, and then use the find method to get the item by id. oh, also, i'm assuming that the db you have in your examples is a DbContext, or something that inherits from DbContext

1
10/30/2013 3:38:03 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow