Entity framework EF代码优先;多对多集合为空?

Entity framework EF代码优先;多对多集合为空?,entity-framework,many-to-many,entity-relationship,Entity Framework,Many To Many,Entity Relationship,对于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; s

对于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;}
}
公共类1{
[关键]
公共int Id{get;set;
公共列表其他对象{get;set;}
}
公共课2{
[关键]
公共int Id{get;set;
公共列表其他对象{get;set;}
}
在别的地方

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

c.OtherObjects.Add(new Class2());
class1c=新的Class1{
OtherObjects=new List();//必要吗?我必须这样做吗?
};
c、 添加(新类2());

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

您必须这样做。或者,您可以在y中实例化集合我们的构造师

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

假设下面的类

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;}
}
但是,如果以另一种方式进行分配,则必须实例化集合

Class2 class2 = new Class2();
class2.OtherObjects = new List<Class1>(); //required
class2.OtherObjects.Add(new Class1());
Class2 Class2=newclass2();
class2.OtherObjects=新列表();//必需
添加(新的Class1());

我也不知道。但它奏效了……我会密切关注这种行为。不过,谢谢你提供的信息!
Class2 class2 = new Class2();
class2.OtherObjects = new List<Class1>(); //required
class2.OtherObjects.Add(new Class1());