EF InsertOrUpdate problem

I have no problem inserting into the database, but when I did the update process, the following problems appear.

Additional information: the binding of an object of type 'kgSoft_Pro.ORM.Models.StokKarti' failed because another object of the same type already has the same primary key value. This can happen when using the “Attach” method or setting the state of an object to “No change” or “Modified” if any objects on the chart have conflicting key values. This may be due to the fact that some objects are new and have not yet received the database key values. In this case, use the "Add" or "Added" state of the object to track the chart, and then set the state of not new objects to "No change" or "Modified" as necessary.

AddOrUpdate Code

public int InsertOrUpdate(T Entity) 
{
    var type = Entity.GetType();
    var property = type.GetProperty("id");
    var propValue = (int)property.GetValue(Entity);
    dbContext.Entry(Entity).State = propValue > 0 ? EntityState.Modified : EntityState.Added;
    return Save();
}

Save Codes

StokKarti stok = new StokKarti();
stok.Adi = txtStokAdi.Text;
stok.AlisFiyati = decimal.Parse(clcAlisFiyati.EditValue.ToString());
stok.StokKodu = btnStokKodu.EditValue.ToString();
stok.Barkod = txtBarkod.Text;
stok.DigerSatis = decimal.Parse(clcDigerFiyat.EditValue.ToString());
stok.GrupKod = lkGrupKodlari.EditValue.ToString();
stok.hizlisatis = chkSatisEkrani.Checked;
stok.PerakendeSatis = decimal.Parse(clcPerakende.EditValue.ToString());
stok.ToptanSatis =decimal.Parse(clcToptanFiyat.EditValue.ToString());
stok.RiskLimiti = (int?)txtRiskLimiti.EditValue ?? 0;
stok.KdvOrani = (int)lkKdvOran.EditValue;
stok.Birim = lkBirim.EditValue.ToString();
stok.Marka = lkMarkasi.EditValue.ToString();
stok.id = id;
sk.InsertOrUpdate(stok);
+3
1
dbContext.DbSet<T>().AddOrUpdate(Entity)

+3

Source: https://habr.com/ru/post/1659348/


All Articles