【问题标题】:Can I prevent EF CF from trying to modify an 'Identity' column in database? Getting "Modifying a column with the 'Identity' pattern is not supported."我可以阻止 EF CF 尝试修改数据库中的“身份”列吗?获取“不支持使用 'Identity' 模式修改列。”
【发布时间】:2015-03-15 16:36:18
【问题描述】:

我的域中存在一对多关系,类似于以下内容:

public class Movie
{
    public int MovieID { get; set; }
    public string MovieName { get; set; }      

    public virtual ICollection<MovieCategory> Categories { get; set; }
}

public class MovieCategory
{
    [Key, ForeignKey("Movie")]
    public int MovieID { get; set; }

    [Key, ForeignKey("Category")]
    public int CategoryID { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public DateTime DateCreated { get; set; }

    public virtual Movie Movie { get; set; }
    public virtual Category Category { get; set; }
}

DateCreated 字段是在 SQL 中通过 GETDATE() 在插入新电影时设置的(并在一堆复选框中选中某些类别)。这部分工作正常。

但是,在编辑电影时,我需要能够更新电影类别的选择(这意味着添加和/或删除其他类别,具体取决于用户对复选框中的选择所做的操作)。我试过这个:

public ActionResult Edit(MovieEditViewModel model)
{
    var movie = db.Movies.Find(model.MovieID);

    //clear out all previously selected categories
    movie.Categories.Clear();

    //add the list of selected categories from just-edited movie
    foreach(var catID in model.selectedCategories)
    {
        movie.Categories.Add(new MovieCategory { CategoryID = catID });
    }

    db.Entry(movie).State = EntityState.Modified;
    db.SaveChanges();
}

我猜 EF 很聪明,可以判断哪些类别需要删除,哪些需要添加,哪些需要修改。

唯一的问题是,对于它正在修改的那些,它会尝试修改每个字段,包括 DateCreated 字段,并且由于该字段只应该在插入期间被触及(即“身份”),因此会导致此错误:

"Modifying a column with the 'Identity' pattern is not supported. Column: 'DateCreated'. Table: 'CodeFirstDatabaseSchema.MovieCategory'."

有什么办法可以克服这个问题吗? 我想做的只是让某人编辑一部电影,在编辑过程中可能会或可能不会修改电影类别列表,并且 DB 中的 MovieCategory 表需要准确反映编辑后的选择。强>

我也尝试添加这个,但没有改变:

foreach(var category in movie.Categories)
{
    db.Entry(category).Property(c => c.DateCreated).IsModified = false;
}

【问题讨论】:

    标签: c# asp.net-mvc ef-code-first entity-framework-6


    【解决方案1】:

    DatabaseGeneratedOption.Identity 用于标识列。这些也是自动生成的,但从不打算修改它们,因为这些列通常用作主键。

    您应该将选项更改为

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime DateCreated { get; set; }
    

    执行此操作时,EF 将忽略插入和更新语句中的属性,并在这些语句之后立即从数据库中读取其值。

    如果您这样做,您的代码应该可以正常运行。

    旁注,声明

    db.Entry(movie).State = EntityState.Modified;
    

    是多余的,因为它只影响movie 的标量属性,而不影响它的Categories。而movie本身并没有被修改。

    【讨论】:

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