【问题标题】:Entity Framework doesn't save实体框架不保存
【发布时间】:2012-08-05 16:22:01
【问题描述】:

我正在尝试更新我的表 Bareme,但我的唯一键 (Categorie , Section) 出现异常,但如此处所示,如果对象确实存在,我只会更新我的薪水,并且我已通过“DEBUG”验证插入的对象都没有重复

内部异常说:

违反 UNIQUE KEY 约束“IX_Bareme”。无法在对象 'dbo.Bareme' 中插入重复键。\r\n语句已被 终止。

代码:

for (int i = 1; i <= sl_cat.Value; i++)
            for (int j = 1; j <= sl_sec.Value; j++)
            {

                Bareme brm = db.Entities.Baremes.Select(X => X).Where(X => X.Section == j && X.Categorie == i).FirstOrDefault();
                if (brm != null)
                    db.Entities.Baremes.DeleteObject(brm);

                brm = new Bareme();
                brm.Categorie = i;
                brm.Section = j;
                brm.Salaire = dt.Rows[j - 1][i.ToString()].ToString().ToDecimal();
                db.Entities.Baremes.AddObject(brm);
            }

        try
        {
            db.Entities.SaveChanges();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

【问题讨论】:

  • 当您执行 AddObhject() 时,所有行都将具有相同的 ID BRM。可以吗???
  • 即使我像这样更新了我的代码,即使我添加了@HatSoft 的SaveOptions.DetectChangesBeforeSave,它也不起作用

标签: c# linq entity-framework entity-framework-4 linq-to-entities


【解决方案1】:

请使用SaveChanges MethodSaveOptions 代表DetectChangesBeforeSave

示例

db.Entities.SaveChanges(SaveOptions.DetectChangesBeforeSave);

【讨论】:

  • @SéddikLaraba 你遇到了什么异常
  • an error occured while updating the entity, see inner exception for more details里面的异常写在问题里
  • 抱歉,我之前忘记了一些更改,现在效果很好,谢谢
  • @SéddikLaraba 没问题,伙计,我很高兴它为你解决了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多