Why reference properties works only through context

I solved second issue (A parameterless constructor was not found... exception) like this:

  1. I setted default constructor of Entity class and sub entities as protected

  2. When I load entity from DB Context property of entities will be null, because EF uses default constructor. That's why I created my own IQuerable collection. It sets Context property when it's not setted:

    class IContextable<T> : IQueryable<T> where T : Entity {

    public IQueryable<T> SourceQuery { get; set; }
    public KitchenAppContext Context { get; set; }
    public IContextable(IQueryable<T> query, KitchenAppContext context)
    {
        SourceQuery = query;
        Context = context;
    }
    
    public Type ElementType => SourceQuery.ElementType;
    
    public Expression Expression => SourceQuery.Expression;
    
    public IQueryProvider Provider => SourceQuery.Provider;
    
    public IEnumerator<T> GetEnumerator()
    {
        foreach (var entity in SourceQuery)
        {
            if (entity.Context == null || entity.Context != Context)
                entity.Context = Context;
            yield return entity;
        }
    }
    
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
    }
    

And my GetEntities method in my Context class:

public IQueryable<T> GetEntities<T>() where T : Entity
    {
        IQueryable<T> query = Set<T>();
        return new IContextable<T>(query, this);
    }

Maybe, there was better ways, but I couldn't found them. It works now, but I'm still waiting for good answer

Tags:

C#

Ef Core 2.0