0

I am using a dynamic way of including "parent properties" when i am retrieving entities from the db. However, since that checks if the property is a value type (or string) or an ienumerable of something (excluding those), it will also include entities that are defined as complextypes. This will lead to an exception.

Is it possible to check if an entity has been defined as a complex type?

Please see this example code:

public IEnumerable<object> LookupExtent(Type type)
{
        var set = Set(type);

        DbQuery q = null;

        foreach (var prop in type.GetParentProperties())
        {
            if (q == null)
                q = set.Include(prop.Name);
            else
                q = q.Include(prop.Name);
        }

        return q.ToObjectArray();
    }

PS: Yes i know this will fail if i have no parent properties...

1 Answers1

0

It have much more problems. What happens if your entity contains some additional unmapped properites? You can ask EF to give you names of all mapped navigation properties. It is little science to get information from EF metadata but it is possible. Try something like this (the code expects that you are using DbContext API but it can be easily changed to ObjectContext API):

ObjectContext objectContext = ((IObjectContextAdapter) dbContext).ObjectContext;
MetadataWorkspace workspace = objectContext.MetadataWorkspace;
EntityContainer container = 
    workspace.GetEntityContainer("NameOfYourContextClass", true, DataSpace.CSpace);
EntitySet entitySet = 
    container.GetEntitySetByName("NameOfYourPropertyExposingDbSetOnTheContext", true);
IEnumerable<string> navigationPropertyNames = 
    entitySet.ElementType.NavigationProperties.Select(n => n.ToString());

The key is providing correct names into GetEntityContainer and GetEntitySetByName and it is also the main difference between code first and db / model first. If you are using code first these names follows some conventions. If you are using EDMX you can control these names in the designer.

Anyway this automagic Include is something you should avoid to use. Include only data your really need and do it explicitly to always show the complexity of the query.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I understand your concerns and what i am trying to achieve is not the "default use case". I will only use this automagic on very special cases. The default case does not include any parent or child properties and the loading of those has to be explicitely stated. I will give your code a try and mark yours as answer when i am back in office (next monday) so youll have to wait a bit ;-) –  Feb 16 '12 at 09:58