2

I don't have any problem when inserting into the database, but when I did the update process, the following issues emerge.

Additional information: Attaching an entity of type 'kgSoft_Pro.ORM.Models.StokKarti' failed because another entity 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 entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

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);
Cœur
  • 32,421
  • 21
  • 173
  • 232
KdrGny
  • 140
  • 11

1 Answers1

2
dbContext.DbSet<T>().AddOrUpdate(Entity)

problem solved

KdrGny
  • 140
  • 11
  • [and new problem introduced!](http://thedatafarm.com/data-access/take-care-with-ef-4-3-addorupdate-method/) – gbjbaanb Sep 03 '19 at 17:07