Rand Random
Rand Random

Reputation: 7440

Cast DbSet<T> and call method

I am trying to write a method that casts a property to DbSet and than calls the load method.

I have tried the following:

var value = propertyInfo.GetValue(em, null) as DbSet;
//Not working, because it always returns null

var value = propertyInfo.GetValue(em, null) as DbSet<T>;
//Not working, because its a syntax error and doesnt even compile (giving error 'Cannot resolve symbol T')

var value = propertyInfo.GetValue(em, null) as DbSet<TEntity>;
//Not working, because its a syntax error and doesnt even compile (giving error 'Cannot resolve symbol TEntity')

But only when I specify the correct type its working:

var value = propertyInfo.GetValue(em, null) as DbSet<TempTable>;

How can I solve this with out specifying TempTable?

Upvotes: 1

Views: 996

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062510

var value = propertyInfo.GetValue(em, null) as DbSet;
//Not working, because it always returns null

Indeed; DbSet<TEntity> does not inherit from DbSet, so yes, that will always be null.

//Not working, because its a syntax error and doesnt even compile (giving error 'Cannot resolve symbol T')

You need to know the type of something to talk to it; you could use the non-generic IEnumerable / IQueryable APIs, but I suspect the most appropriate evil here might be dynamic:

dynamic val = propertyInfo.GetValue(em, null);
EvilMethod(val);

//...

void EvilMethod<T>(DbSet<T> data)
{
    // this will resolve, and you now know the `T` you are talking about as `T`
    data.Load();
}

or if you just want to call Load:

dynamic val = propertyInfo.GetValue(em, null);
val.Load();

Upvotes: 4

Reda
Reda

Reputation: 2289

Try this:

var value = propertyInfo.GetValue(em, null) as IQueryable;
value.Load();

Upvotes: 3

Mikael &#214;stberg
Mikael &#214;stberg

Reputation: 17146

Something like this perhaps:

var setMethod = typeof(MyDataContext)
    .GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
    .Where(m => m.Name == "Set")
    .Where(m => m.IsGenericMethod)
    .Select(m => m.MakeGenericMethod(typeof(TEntity)))
    .SingleOrDefault();

var value = setMethod.Invoke(myDataContextInstance, null);

Upvotes: 1

Related Questions