Hasan
Hasan

Reputation: 2552

context.SaveChanges() gives error upon Adding

Using this code I get no errors

   public static void kirisekle(string kirisadi, int genislik, int derinlik, int uzunluk, int katid)
    {
        Beam newbeam = new Beam { Kirisadi = kirisadi, Genişlik = genislik, Derinlik = derinlik, Uzunluk = uzunluk, KatID = katid };
        using (pehkEntities context = new pehkEntities())
        {

            context.Beams.Add(newbeam);
            context.SaveChanges();
        }
    }

However, I get "dbupdateexception was unhandled" error while using this code

public static void dosemeekle(string dosemeadi, int en, int boy, int kalinlik, int katid)
    {
        Slab newslab = new Slab { DosemeAdi = dosemeadi, En = en, Boy = boy, Kalınlık = kalinlik, KatID = katid };
        using (pehkEntities context = new pehkEntities())
        {

            context.Slabs.Add(newslab);
            context.SaveChanges();
        }
    }

How should I find the reason for this error and fix it?

I am using this code to see the inner exception:

context.Slabs.Add(newslab);
        try
        {
            context.SaveChanges();
        }
        catch( System.Data.Entity.Infrastructure.DbUpdateException ex)
        {
            MessageBox.Show(ex.InnerException.Message);

        }

However, it shows a messagebox says "an error occured updating the entries. See the inner exception for details." only.

Upvotes: 3

Views: 21544

Answers (1)

Kamil Krasinski
Kamil Krasinski

Reputation: 529

Try to have a look at your table definition in SQL:

  • are all non-null fields provided in code?

  • when exception happen is the length of string exceeded

  • are you using primary key, which already exists in database?

These are most likely reasons for exception if there are no connection issues. I am assuming so since the first method works.

Upvotes: 10

Related Questions