【发布时间】:2016-04-20 14:28:29
【问题描述】:
我的 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;
}
}
当我调用此方法时,我在foreach 循环中的行中得到一个NullReferenceException,它将Category 对象添加到article.Categories 集合中。
显然,Categories 集合没有在对 new Article() 的调用中初始化。我错过了什么?
【问题讨论】:
标签: c# entity-framework entity-framework-6 many-to-many