多对多导航属性为null
本文关键字:null 导航 属性 | 更新日期: 2024-10-18 11:13:49
我的EF6代码优先模型中有这两个类:
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;
}
}
当我调用这个方法时,我在foreach
循环中的行上得到一个NullReferenceException
,它将Category
对象添加到article.Categories
集合中。
显然,Categories
集合在对new Article()
的调用中没有初始化。我错过了什么?
为了避免这种异常,我总是在一个空构造函数中初始化集合属性:
public class Article
{
public Article()
{
Categories =new List<Category>();
}
//...
}
不能将项添加到null集合中。您需要将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>()
};