Search code examples
c#entity-frameworkef-code-first

Get all model types


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>.


Solution

  • 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 = objContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.OSpace).Select(x => Type.GetType(x.FullName));
    foreach (var t in lst) {
    ...