Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll

I wrote a rather simple code (client server based on WCF and Windows form). i was trying to update the db so that i could test my code and i encounterd the above exception. Any ideas how to solve it?

      // For testing 
      public void updateTable() 
      {
        using (var db = new overlayDBEntities())
        {
            var overlaydb = new overlayData
            {
                DeviceId = "1111",
                TimestampUTC = new DateTime(1990, 1, 1, 9, 9, 9),
                OverlayData1 = "Random Text"
            };

            db.overlayData.Add(overlaydb);

            try
            {
                db.SaveChanges();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            var overlaydb1 = new overlayData
            {
                DeviceId = "1111",
                TimestampUTC = new DateTime(2000, 2, 2, 10, 10, 10),
                OverlayData1 = "seconed seconed seconed "
            };

            db.overlayData.Add(overlaydb);

            try
            {
                db.SaveChanges();
            }
            catch (Exception ec) 
            {
                Console.WriteLine(ec.Message);
            }
        }
    }
like image 923
user2656851 Avatar asked Oct 17 '13 10:10

user2656851


3 Answers

If you need to update Row if already Exists in database so dont use context.Add();you can use as follows.

    var overlaydb1 = new overlayData
    {
      DeviceId = "1111",
      TimestampUTC = new DateTime(2000, 2, 2, 10, 10, 10),
      OverlayData1 = "seconed seconed seconed "
    };

    try
    {
      db.overlayData.Attach(overlaydb1);
      db.ObjectStateManager.ChangeObjectState(overlaydb1, EntityState.Modified);
      db.SaveChanges();
    }

    catch (Exception ec) 
    {
      Console.WriteLine(ec.Message);
    }
like image 189
Thilina H Avatar answered Oct 09 '22 22:10

Thilina H


This same Error is also appear when user forget to add Primery key in particular table .. and then add data through application.

like image 31
Usman lqbal Avatar answered Oct 09 '22 20:10

Usman lqbal


I think the problem is the type of your datetime. sqlsever has more than one datetime. if you check your inner exception, you may see the type that you are trying to put in your table and the type it actually needs. conversion cant be done automatically and you should change it in the table or convert it in your code. it can be datetime, datetime2 (7), etc.

like image 37
noushin joudzadeh Avatar answered Oct 09 '22 20:10

noushin joudzadeh