1

使用 EF 多对多关系,我是否必须手动实例化相应的对象集合?

像...

public class Class1 {
  [Key]
  public int Id { get; set;
  public List<Class2> OtherObjects {get; set;}
}

public class Class2 {
  [Key]
  public int Id { get; set;
  public List<Class1> OtherObjects {get; set;}
}

还有别的地方...

Class1 c = new Class1 {
  OtherObjects = new List<Class2>(); // necessary? Do I have to do this?
};

c.OtherObjects.Add(new Class2());

像这样?因为当我建立一对多关系时,集合似乎是自动实例化的。这与多对多关系不同吗?或者当集合OtherObjects为空时,我的应用程序中是否存在错误或不当行为?

4

1 回答 1

2

你必须这样做。或者,您可以在构造函数中实例化集合。

旁注:当我有一对多时,我需要实例化我的集合。我不确定你为什么不需要。

假设下面的类。

public class Class1 {
  [Key]
  public int Id { get; set;
  public Class2 OtherObject {get; set;}
}

public class Class2 {
  [Key]
  public int Id { get; set;
  public List<Class1> OtherObjects {get; set;}
}

你可以这样做

Class1 class1 = new Class1();
class1.OtherObject = new Class2();

但是,如果您以其他方式执行分配,则必须实例化您的集合。

Class2 class2 = new Class2();
class2.OtherObjects = new List<Class1>(); //required
class2.OtherObjects.Add(new Class1());
于 2012-09-26T13:52:01.620 回答