【问题标题】:Model includes list of objects模型包括对象列表
【发布时间】:2015-05-28 18:49:20
【问题描述】:

我尝试构建一个包含多个属性和对象列表的模型,如下所示:

public class A
{
    public int ID { get; set; }
    public string AnyProperty { get; set; }
}

public class B
{
    public int ID { get; set; }
    public string Title { get; set; }
    public List<A> AList {get; set;}
}

问题是,在用于创建类型 A 对象的控制器中,我想创建一个新列表“As”并将其添加到类型 B 的(现有或新)对象中。 所以我写:

db.Bs.Find(id).AList = new List<A> {a};

但在 B 的详细信息视图中调用此 List 后,它总是显示 NullReferenceException,因为 AList 仍然为空。 似乎数据库不安全 AList,我该怎么做才能保护列表?

【问题讨论】:

  • 什么是分贝?你使用实体框架吗?
  • db 是 A 和 B 的 databaseContext。我必须使用公共虚拟 A {get; set;} 或者我可以用 Lists 做到这一点吗?

标签: asp.net entity-framework asp.net-mvc-4 model


【解决方案1】:

一对多关系必须声明为virtual ICollection&lt;&gt;

public class B
{
    public int ID { get; set; }
    public string Title { get; set; }
    public virtual ICollection<A> AList {get; set;}
}

而且您不必实例化成员AList。只需将它添加到您的 A 对象即可。

db.Bs.Find(id).AList.Add(a);

【讨论】:

  • 非常感谢,这对我有用,现在看来可以了。很棒的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 2018-11-30
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
相关资源
最近更新 更多