Reputation: 1522
I have a DbSet<T>
, where T is unknown at compile time, that is given to me from Reflection. I would like to unpack it and work with the methods available to me in the non-generic DbSet
Class. However:
((DbSet)MyDbSetAsObject).Attach(MyValue); //InvalidCastException, can't cast from DbSet<T>to DbSet.
Am I missing something here? this seems like a personally reasonable thing to do
Upvotes: 0
Views: 201
Reputation: 49095
The generic DbSet<>
contains an implicit conversion to the non-generic DbSet
:
// Summary:
// Returns the equivalent non-generic System.Data.Entity.DbSet object.
//
// Returns:
// The non-generic set object.
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Intentionally just implicit to reduce API clutter.")]
public static implicit operator DbSet(DbSet<TEntity> entry);
That means you can simply write:
DbSet nonGenericSet = myGenericSet;
You could also try (as already proposed by @Lorentz Vedeler):
DbSet nonGenericSet = this.Set(typeof(myRunTimeEntity));
Upvotes: 1
Reputation: 5301
Use this Method to retrieve a set for the given type.
var dbSet = MyContext.Set(MyType);
dbSet.Attach(MyValue);
Upvotes: 2