c# – Property of a class that belongs to another context in the Entity Framework

Question:

I have a class called Locker that has the following property:

public virtual ICollection<LockerReserve> Reserves { get; set; }

The problem is that LockerReserve belongs to a different context than Locker. An exception is thrown whenever I try to retrieve a locker as it cannot get the LockerReserve list.

public Locker GetLockerById(int lockerId)
{
    var lockers = _lockerContext.Lockers
        .Where(b => b.LockerId == lockerId);

    return lockers.FirstOrDefault();
}

Is it possible for a class to have a list of a type that is not in its context in the Entity Framework?

Answer:

Is it possible for a class to have a list of a type that is not in its context in the Entity Framework?

No. Almost certainly it won't work.

The importance of having all the entities mapped in just one context is precisely to guarantee cohesion between the entities. Separating, you have no way of telling the context that that relationship exists, so the pointing out of the exception is correct.

I don't know why you want this separation, but there are better ways to solve the problem. I just need more detail in your question to improve this answer (why the separation, what aspects of this implementation need to be considered, among others).

Scroll to Top
AllEscort