【问题标题】:Many to many navigation property is null多对多导航属性为空
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 那么List 会起作用吗?不一定是DbSet 或其他类型的集合?
【解决方案2】:

您不能将项目添加到空集合。您需要将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>()
};

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多