0

How to get all persitable code first entities for a given DbContext?

I can get all declared DbSet properties from the context throught reflection, but when inheritance comes into play DbSet<TSomeAbstractBaseEntity> is defined for a base abstract entity, and what I really need is the list of concrete descendants that were mapped.

(Yes, I'am aware that there's a dynamic way of connecting entity to the context via DbContext.DbSet<TEntity>() method call. I just ignore this case.)

Pavel Voronin
  • 13,503
  • 7
  • 71
  • 137
  • You already know how to use reflection... reflect over all the types in your assembly and see if they inherit from the types in your DbSets. – Sam Axe Jul 02 '15 at 10:12
  • I immagine you know also Set(Type entityType). Do you need to enumerate DbSets where the entity inherit from another specific class/interface? – bubi Jul 02 '15 at 10:13
  • @bubi, no, I just need to get all 'real' entities. – Pavel Voronin Jul 02 '15 at 10:17
  • @Same Axe This solution has some problems. What if some of inherited intities are not mapped? – Pavel Voronin Jul 02 '15 at 10:17
  • This is not really an answer but you have 2 ways to to see whats mapped. You can use reflection or you can use the model. You can probably retrieve a model in XML (the one that EF writes into __MigrationHistory to see if a migration is required) or you can access the model directly. You can see an approach to access the model here http://stackoverflow.com/questions/14733047/entity-framework-code-first-configure-mapping-for-sqlquery/30777774#30777774 (probably you can find some better way, this is just a start). – bubi Jul 02 '15 at 10:29

1 Answers1

0

I do not know how much this solution is robust, but it gives me what I need.

var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;
var mappedTypes = metadata.GetItemCollection(DataSpace.CSSpace)
    .GetItems<EntityContainerMapping>()
    .Single()
    .EntitySetMappings
    .Select(
        m =>
            new
            {
                SetType = m.EntitySet.ElementType,
                Types =
                    m.EntityTypeMappings
                        .Where(tm => tm.EntityType != null && !tm.EntityType.Abstract)                          .Select(tm => tm.EntityType)
                        .ToList()
            });
Pavel Voronin
  • 13,503
  • 7
  • 71
  • 137