我尝试构建一个包含多个属性的模型和一个像这样的对象列表:
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仍然为null。 似乎数据库不安全AList,我该怎样做才能安全列表?
答案 0 :(得分:1)
必须将一对多关系声明为virtual ICollection<>
。
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);