Why does Entity Framework return null List<> instead of empty ones?

前端 未结 3 1817
终归单人心
终归单人心 2021-01-01 09:35

I\'m pretty new in the ASP .NET MVC world. Maybe, that\'s the reason I can\'t explain to myself the cause of what is, for me, an annoying problem.

I have one class w

相关标签:
3条回答
  • 2021-01-01 10:08

    You should have your entity create those lists in the constructor. EF doesn't create dependent collections, and expects the entity to do so.

    So, your case, you would make your entity like this:

    class MyClass{ 
        public List<OtherClass> _otherClasses {get;set;} 
    
        public MyClass() {
            _otherClasses = new List<OtherClass>();
        }
    } 
    
    0 讨论(0)
  • 2021-01-01 10:08

    So, if I understand correctly, you are adding an empty List<OtherClass> to the context and then trying to retrieve it.

    I guess you have to think about how the context will track and query entities that are in its context. This is usually done by the Key of the entity. In your example, you have not given the entity a Key, therefore, the context has no handle on the entity.

    Therefore, when you query, the context doesn't find an object and returns null.

    If you want to initialize a new entity, I would recommend to give it at least a Key (usually the Id property), and then select by that key when you lookup later.

    Hope this helps.

    0 讨论(0)
  • 2021-01-01 10:11

    Make the otherClasses collection virtual. This will enable EF to lazy load the collection.

    class MyClass{
        public virtual List<OtherClass> otherClasses {get;set;}
    }
    

    Otherwise use eager loading with Include method.

    context.myClass.Include(m => m.otherClasses).SingleOrDefault(m => m.Id == foo);
    
    0 讨论(0)
提交回复
热议问题