The property 'name' is part of the object's key information and cannot be modified. Entity Framework

后端 未结 6 1678
无人共我
无人共我 2020-11-29 11:00

I am trying to update a record and I get this error message after the context.SaveChanges();

The property \'name\' is part of the object\

6条回答
  •  有刺的猬
    2020-11-29 11:44

    Same happened to me today. I set new entity's ID with the old record's ID and the error is gone.

    //This checks whether there's a record with same specific data.
    var kayitVarMi = _db.Sorgu.FirstOrDefault(a => a.Serial == sorgu.Serial);
    
                    if (kayitVarMi != null) // If there's
                    {
                        sorgu.Id = kayitVarMi.Id; //This one does the trick
                        _db.Entry(kayitVarMi).CurrentValues.SetValues(sorgu);
                    }
                    else // If not
                    {
                        _db.Sorgu.Add(sorgu);
                    }
    
                    // This whole block is in a transaction scope so I just check recordability.
                    if (_db.SaveChanges() > 0)
                    {
                        _sorguKaydedildiMi = true;
                    }
    

提交回复
热议问题