简体   繁体   English

实体框架不保存

[英]Entity Framework doesn't save

I am trying to update my table Bareme but I get an exception about my unique key (Categorie , Section) , but as seen here am updating only my salary if the object does exist, and I've verified by "DEBUG" that none of the inserted objects is duplicated 我正在尝试更新我的表Bareme但是我得到了一个关于我的唯一密钥(Categorie , Section)的例外,但正如此处所见,如果对象确实存在,我只更新我的工资,并且我已通过“DEBUG”验证没有插入的对象是重复的

The inner exception says : 内部例外说:

Violation of UNIQUE KEY constraint 'IX_Bareme'. 违反UNIQUE KEY约束'IX_Bareme'。 Cannot insert duplicate key in object 'dbo.Bareme'.\\r\\nThe statement has been terminated. 无法在对象'dbo.Bareme'中插入重复键。\\ r \\ n语句已终止。

Code: 码:

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);
        }

Please use the SaveChanges Method with SaveOptions for DetectChangesBeforeSave 请使用SaveChanges MethodSaveOptions for DetectChangesBeforeSave

Example

db.Entities.SaveChanges(SaveOptions.DetectChangesBeforeSave);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM