我的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()
集合。我错过了什么?
答案 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>();
}
//...
}