adeveloper
adeveloper

Reputation: 311

EF throws exception after second update attempt

There is an update method throws exception but it works fine in first loging after second attempt throws exception with message; **

Additional information: Attaching an entity of type 'Hsys.InfluenzaTaniBilgisi' 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.

** Iknow its common and found many smilar issue but I couldnt make it work..

here is code piece;

public void CreateUpdateInfluenzaTani(InfluenzaTaniBilgisi taniBilgisi)
            {
                using (HsysDbContext con = new HsysDbContext())
                {

                    if (con.InfluenzaTestTanilari.Any(x => x.ICD10TaniKodu == taniBilgisi.ICD10Kodu && x.IsDeleted != true))
                    {
                        var taniExist = con.InfluenzaTaniBilgisi.FirstOrDefault(x => x.MuayeneId == taniBilgisi.MuayeneId && x.ICD10K

odu == taniBilgisi.ICD10Kodu && x.IsDeleted != true);
                        if (taniExist == null)
                        {
                            taniBilgisi.ObjectState = Framework.Entities.ObjectState.Added;
                            Create(taniBilgisi);
                        }
                        else
                        {
                            taniExist.HastaYasi = taniBilgisi.HastaYasi;
                            taniExist.HekimTC = taniBilgisi.HekimTC;
                            taniExist.ObjectState = Framework.Entities.ObjectState.Modified;
                            Update(taniExist);// throws Exception!
                        }
                    }
                }
            }

Upvotes: 0

Views: 41

Answers (1)

Barr J
Barr J

Reputation: 10919

 taniExist.ObjectState = Framework.Entities.ObjectState.Modified;

This is your issue.

You cannot use the Framework.Entities.ObjectState.Modified; on an existing key, entity frame work won't allow that.

You need to first do this:

taniExist.ObjectState = Framework.Entities.ObjectState.Added;

and then:

  taniExist.ObjectState = Framework.Entities.ObjectState.Modified;

Your code will look like this:

      taniExist.HastaYasi = taniBilgisi.HastaYasi;
                            taniExist.HekimTC = taniBilgisi.HekimTC;
                            taniExist.ObjectState = Framework.Entities.ObjectState.Added;
                            Update(taniExist);
Framework.Entities.ObjectState.Modified;

Upvotes: 1

Related Questions