user290043
user290043

Reputation:

How to get the correct DB Entity at Runtime?

In my method:

public void DeleteSingleMrTypeByVersionIdAndId<T>(
    int version_id, int child_obj_id, CIHEntities _dbContext)
        where T : MrBase

I want to fetch the row from a DB entity. So, I have this:

IQueryable<T> old_items = _dbContext.???
            .Where(r => r.MrVersionEntityAssoc.Id == version_id)
            .Where(r => r.Id == child_obj_id)
            .Select(r => r);

But how do I write the LINQ statement so that it uses T to know where to get the row from?

Of course, just referring to it as T does not work.

IQueryable<T> old_items = _dbContext.T
            .Where(r => r.MrVersionEntityAssoc.Id == version_id)
            .Where(r => r.Id == child_obj_id)
            .Select(r => r);

We are using VS2012.

Thanks Eric

Upvotes: 3

Views: 209

Answers (1)

vzwick
vzwick

Reputation: 11044

The method you're looking for is Set():

IQueryable<T> old_items = _dbContext.Set<T>()
    .Where(r => r.MrVersionEntityAssoc.Id == version_id)
    .Where(r => r.Id == child_obj_id)
    .Select(r => r);

Edit: The above applies when using DbContext. For ObjectContext, the corresponding method is CreateObjectSet<T>().

IQueryable<T> old_items = _dbContext.CreateObjectSet<T>()
    .Where(r => r.MrVersionEntityAssoc.Id == version_id)
    .Where(r => r.Id == child_obj_id)
    .Select(r => r);

Upvotes: 3

Related Questions