How can I get a list of entity types that are part of the model, so I can test that the model actually works with that entity type?
var dcx = new MyDbContext();
var lst = new List<Type>();
//populate the list here somehow
//...
foreach (var t in lst) {
var set = dcx.Set(t); //I'm trying to avoid an exception here
try {
var test = set.FirstOrDefault();
} catch (Exception ex) {
Console.WriteLine("{0} has an error", t);
}
}
NB: It is perfectly possible to query dcx.Set(t)
even if there is no corresponding DbSet
property on MyDbContext
; therefore it's not enough to iterate via reflection over the properties of MyDbContext
whose return type's generic definition is DbSet<T>
or even IDbSet<T>
.
Maybe something like this?
var types = typeof(MyDbContext)
.GetProperties()
.Where(prop => prop.PropertyType.IsGenericType)
.Where(prop => prop.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
.Select(prop => prop.PropertyType.GenericTypeArguments.First())
.Distinct();
Zev Spitz
Thanks to the link in @GertArnold 's comment, I am now using the following:
var dcx = new MyDbContext();
var objContext = ((IObjectContextAdapter)dcx).ObjectContext;
var types = db.ObjectContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.OSpace).Select(x => Type.GetType(x.FullName));
foreach (var t in lst) {
...
来源:https://stackoverflow.com/questions/33928716/get-all-model-types