EF 4.0 - Download the navigation property of the navigation property

I am trying to perform a LoadProperty operation from my context to load a navigation property of a navigation property.

My setup is that I have an EntityA that contains an EntityB list, and each EntityB contains an EntityC list. I am doing the following programmatically:

public virtual List<T> LoadProperty(List<T> entities, string property)
{
    using (MyContext context = new MyContext())
        foreach (T entity in entities)
        {
            context.AttachTo(typeof(T).Name, entity);
            context.LoadProperty(entity, property);
        }

    return entities;
}

I call it the following:

LoadProperty(entityA, "EntityB.EntityC");

I know that the NavigationProperty path is correct, however this does not work. Is there any way to download this?

Edit: Working example using Includes:

using (MyContext context = new MyContext())
{
    var query = from entityA in context.EntityA.Include("EntityB").Include("EntityB.EntityC")
                where entityA.Id == id
                select entityA;

    return query.ToList();
}
+3
source share
2 answers

-, call context.AttachTo(typeof (T).Name, entity) , InvalidOperationException. ObjectContext.AttachTo :

public void AttachTo(string entitySetName, Object entity)

, EntitySet, Entity. , EntitySet MetadataWorkspace, Entity. .

, 3 , EntityB EntityC EntityCollections, , LoadProperty, LoadProperty , :

using System.Data.Metadata.Edm;

public virtual List<T> LoadProperty(List<T> entities, string property) {
    using (TrialsContext context = new TrialsContext()) {

        EntityContainer container = context.MetadataWorkspace
                                           .GetEntityContainer(context.DefaultContainerName,
                                                               DataSpace.CSpace);
        EntitySetBase entitySet = container.BaseEntitySets
                                           .Where(item => 
                                                  item.ElementType.Name.Equals(typeof(T).Name))
                                           .FirstOrDefault();

        foreach (T entity in entities) {
            context.AttachTo(entitySet.Name, entity);
            context.LoadProperty(entity, property);
        }

    return entities;
}

:


// To load EntityA Nav property:
LoadProperty(entityB, "EntityA");

// To Load EntityC Nav property: 
//Let assume the nav property name for EntityC on EntityB is EntityCList
LoadProperty(entityB, "EntityCList");

, .

+1

" , NavigationProperty ..." , . , . Include, . 1: *.

, , , , .

+1

Source: https://habr.com/ru/post/1762694/


All Articles