多对多导航属性为null

时间:2016-04-20 14:28:29

标签: 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 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; }

}

我在我的数据访问层中有这个代码来创建一篇新文章:

public Article AddArticle( string articleName, int[] categoryIds ) {
    if ( string.IsNullOrWhiteSpace( articleName ) )
        throw new ArgumentNullException( nameof( articleName ), Properties.Resources.ArticleNameWasNull );
    if ( categoryIds == null )
        throw new ArgumentNullException(nameof(categoryIds), Properties.Resources.CategoryIdsAreNull );

    using ( var context = new ArticleContext() ) {
        var article = new Article {
            ArticleName = articleName
        };
        foreach ( var category in context.Categories.Where( c => categoryIds.Contains( c.CategoryId ) ) )
            article.Categories.Add( category );
        context.Articles.Add( article );
        context.SaveChanges();
        return article;
    }
}

当我调用此方法时,NullReferenceException循环中的行foreach会将Category对象添加到article.Categories集合中。

显然,在Categories的调用中未初始化new Article()集合。我错过了什么?

2 个答案:

答案 0 :(得分:1)

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

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

foreach ( var category in context.Categories.Where( c => categoryIds.Contains( c.CategoryId ) ) )
    article.Categories.Add( category );

或者在创建对象的位置添加它:

var article = new Article {
    ArticleName = articleName,
    Categories = new List<Category>()
};

答案 1 :(得分:1)

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

public class Article 
{
   public Article()
   {
      Categories =new List<Category>();
   }
   //...
}