Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 多对多导航属性为空_C#_Entity Framework_Entity Framework 6_Many To Many - Fatal编程技术网

C# 多对多导航属性为空

C# 多对多导航属性为空,c#,entity-framework,entity-framework-6,many-to-many,C#,Entity Framework,Entity Framework 6,Many To Many,我的EF 6代码优先模型中有两个类: public class Category { public int CategoryId { get; set; } [Required, MaxLength( 128 ), Index( IsUnique = true)] public string CategoryName { get; set; } public string Description { get; set; } public virtu

我的EF 6代码优先模型中有两个类:

public class Category {

    public int CategoryId { get; set; }

    [Required, MaxLength( 128 ), Index( IsUnique = true)]
    public string CategoryName { get; set; }

    public string Description { get; set; }

    public virtual ICollection<Article> Articles { get; set; }
}

public class Article {

    [DatabaseGenerated( DatabaseGeneratedOption.Identity ), Key]
    public int ArticleId { get; set; }

    [Required, MaxLength( 128 ), Index( IsUnique = true )]
    public string ArticleName { get; set; }

    public virtual ICollection<Category> Categories { get; set; }

    public string Description { get; set; }

}
调用此方法时,我在
foreach
循环的行上得到一个
NullReferenceException
,该循环将
Category
对象添加到
article.Categories
集合中


显然,
Categories
集合没有在调用
newarticle()
时初始化。我错过了什么

无法将项添加到空集合。您需要将
article.Categories
初始化为新集合

article.Categories = new List<Category>();

foreach ( var category in context.Categories.Where( c => categoryIds.Contains( c.CategoryId ) ) )
    article.Categories.Add( category );
article.Categories=新列表();
foreach(context.Categories.Where(c=>categoryIds.Contains(c.CategoryId))中的变量category)
第条.类别.添加(类别);
或者,将其添加到创建对象的位置:

var article = new Article {
    ArticleName = articleName,
    Categories = new List<Category>()
};
var article=新文章{
ArticleName=ArticleName,
类别=新列表()
};

为了避免这种异常,我总是在空构造函数中初始化集合属性:

public class Article 
{
   public Article()
   {
      Categories =new List<Category>();
   }
   //...
}
公共类文章
{
公共物品()
{
类别=新列表();
}
//...
}

感谢您的回复。我意识到我需要实例化集合。我只是不知道要实例化什么类型的对象,因为
ICollection
是一个接口,而不是一个类,不能实例化。@TonyVitabile您可以使用
List
这样
List
就可以了?它不必是
DbSet
或其他类型的集合?可能是
public class Article 
{
   public Article()
   {
      Categories =new List<Category>();
   }
   //...
}