Question

My Database is set up with an Entity table, which has a Ref_Type navigation property (and a FK which references TypeID). The Type table, has a Ref_Department, same FK setup. Finally, the Department table has a Ref_Locale and same FK setup.

I save the Entities in a List, which is a property of a singleton. It is created as follows;

private Singleton()
{
    using (Database db = new Database())
    {
        List<Entities> EntityList = db.Entities.ToList<Entities>();
    }
}

This is fine, the navigation properties are ALL loaded and I can access any one of them. The problem comes when I update an Entity entry as follows;

public void UpdateEntity(Entities oldEnt, Entities newEnt)
{
    using (Database db = new Database())
    {
        Entities ent = db.Entities.Where(e => e.EntityName == oldEnt.EntityName).FirstOrDefault();
        ent.EntityName = newEnt.EntityName;
        ent.EntityEmail = newEnt.EntityEmail;
        ...
        ent.EntityType_ID = newEnt.EntityType_ID;
        db.SaveChanges();
    }

    RefreshEntities();
}

public void RefreshEntities()
{
    using (Database db = new Database())
    {
        db.Configuration.LazyLoadingEnabled = false;
        db.SaveChanges();
        EntityList = db.Entities.Include("Ref_EntityType").Include("Ref_EntityPosition").ToList<Entities>();
    }
}

Ref_Entity gets loaded properly, but then within Ref_Entity, Ref_Department is just null. I've tried just using db.Entities.ToList<Entities>(); like in my constructor, no dice. As you can see, I've also tried turning LazyLoading off (I thought I might need to call SaveChanges() for it to actually apply the flag). I've also tried .Include("Ref_Department") but it just complains that it doesn't exist for Entities, which makes sense.

The newEnt that I pass to the UpdateEntity method does not have Ref_Type initialised, I'm working under the assumption that anything not changed in the UpdateEntity method would just stay the same...

So now I'm at a bit of a loss as to what's going on and how to fix it. If anyone could help explain where I'm going wrong or give me some pointers about how to fix my code to make it work, that would be great.

Était-ce utile?

La solution

On a whim, I modified RefreshEntities() to;

EntityList = db.Entities.Include("Ref_EntityPosition").Include("Ref_EntityType").
    Include("Ref_EntityType.Ref_Department").
    Include("Ref_EntityType.Ref_Department.Ref_Locale").ToList<Entities>();

And now I'm getting all the references.

I'm still not sure why it would load all the references in the constructor but not in the RefreshEntities() method, even if the calls are identical, but this solves the problem so I'm happy enough to leave it like that.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top