为什么实体框架返回空列表<>而不是空的? [英] Why does Entity Framework return null List<> instead of empty ones?

查看:251
本文介绍了为什么实体框架返回空列表<>而不是空的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP .NET MVC的世界很新。也许,这是我不能给自己解释的是什么,对我来说,一个恼人的问题的原因的原因。

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.

我有一类具有一到多relashionship。

I have one class with One-To-Many relashionship.

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

当我坚持这样一个实例类,我填写它与空List关系<>

When I'm persisting one instance of this class, I fill it's relationship with an empty List<>

MyClass myClass = new MyClass(){ otherClasses = new List<OtherClass>() }
context.myClass.Add(myClass);

的问题是,当我尝试检索该实例,以任何理由,我尝试访问列表,系统给了我一个空引用异常...

The problem is that, when I try to retrieve that instance, and for any reason, I try to access that list, system gives me a Null Reference Exception...

我的问题是:为什么不回EF空列表而不是空的人呢?特别是在这种情况下,我与一个空表坚持呢?

My question is: why doesn't EF return empty lists instead of null ones? Especially in this case, that I'm persisting it with an empty list?

有什么办法可以避免,如果实例是空verifing?

There's any way to avoid verifing if instances are null?

推荐答案

您应该有你的实体在构造函数中创建这些列表。 EF英孚教育不会产生依赖的集合,预计实体这么做

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>();
    }
} 

这篇关于为什么实体框架返回空列表&LT;&GT;而不是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆