none
Problem updating entry in DB using LINQ

    Question

  • I have a User table, where I want to update if the email is verified.

    This is what I do:

    using (var context = new Entities())
                {
                    UserInfo currentInfo = context.UserInfoes.FirstOrDefault(user => user.UserId == userId);
                    context.Entry(currentInfo).CurrentValues.SetValues(updatedUserInfo);
    
                    try { return context.SaveChanges(); }
                    catch (InvalidOperationException) { /*log this exception*/ }
    
                    return -1;
                }

    Now, this UserInfo table has "name" and Email as mandatory fields. When I try to do "Save Changes" I get

    {"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."}

    It says the Name and Email fields can't be empty.

    I was wondering if someone can please let me know what is wrong.

    Thanks for the help.

    Harsimrat

    Saturday, November 02, 2013 11:29 PM

Answers

  • >>So, there is no clean way of updating any single column in the table using LINQ ?

    So you want to update one specify column.

    For this, please have a try with codes like below:

    using (DataBaseFirstDBEntities db = new DataBaseFirstDBEntities())
                {
                    Order updateOrder = new Order() { OrderID = 4, OrderCode = "005" };
    
                    db.Orders.Attach(updateOrder);
    
                    db.Entry<Order>(updateOrder).Property(o => o.OrderCode).IsModified = true;
    
                    try
                    {
                        db.Configuration.ValidateOnSaveEnabled = false;
                        db.SaveChanges();
                        db.Configuration.ValidateOnSaveEnabled = true;
                    }
                    catch (System.Data.Entity.Validation.DbEntityValidationException e)
                    { }
                }

    This is will only update the column 'OrderCode' with the exist record whose key value is 4.

    Before calling SaveChange(), we need to set db.Configuration.ValidateOnSaveEnabled to be false.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.



    Monday, November 04, 2013 7:40 AM

All replies

  • Hello thukralz,

    It is strange for that, because I made a sample which was the sample as yours, however, it worked fine.

    Please have a look at codes below:

    using (DataBaseFirstDBEntities db = new DataBaseFirstDBEntities())
    
                {
    
                    Order updateOrder = new Order() { OrderID = 4, OrderCode = "005", OrderName = "005" };
    
    
                    Order oldOrder = db.Orders.FirstOrDefault(o => o.OrderID == 4);
    
    
                    db.Entry<Order>(oldOrder).CurrentValues.SetValues(updateOrder);
    
    
      db.SaveChanges();
    
                }
    

    Is that the table userinfo independent or not?

    >>It says the Name and Email fields can't be empty.

    From this, I recommend to check whether the two fields have been set to be null in entity ‘updateUserInfo’.

    Or if we want to know detail error message, we can use codes below to show it:

    using (DataBaseFirstDBEntities db = new DataBaseFirstDBEntities())
    
                {
    
                    Order updateOrder = new Order() { OrderID = 4, OrderCode = "005", OrderName = null };
    
    
                    Order oldOrder = db.Orders.FirstOrDefault(o => o.OrderID == 4);
    
    
                    db.Entry<Order>(oldOrder).CurrentValues.SetValues(updateOrder);
    
    
                    try
    
                    {
    
                        db.SaveChanges();
    
                    }
    
                    catch (System.Data.Entity.Validation.DbEntityValidationException e)
    
                    {
    
                        foreach (var eve in e.EntityValidationErrors)
    
                        {
    
                            System.Diagnostics.Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
    
                                eve.Entry.Entity.GetType().Name, eve.Entry.State);
    
                            foreach (var ve in eve.ValidationErrors)
    
                            {
    
                                System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
    
                                    ve.PropertyName, ve.ErrorMessage);
    
                            }
    
                        }
    
                    }
    
                }
    

    It is appreciate that if you can share the whole table structure and how the entity ‘updateUserInfo’ comes so that we could do a test on it.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, November 04, 2013 2:01 AM
  • The Table Structure from currentinfo Object -

    +  Birthday {4/24/1990 12:00:00 AM} System.DateTime?
      City "Vancouver" string
      CountryDialCode 1 int
      CreatedBy 1 int
    +  CreatedDate {11/3/2013 12:00:00 AM} System.DateTime
      Email "t2@test.com" string
      FullName "Test Account" string
      HasAgreedTerms true bool
      IsEmailVerified false bool
      IsPhoneVerified false bool
      ModifiedBy 1 int
    +  ModifiedDate {11/3/2013 12:00:00 AM} System.DateTime
      Number "604SOMETHING" string

      UserId 1039 int

    UpdateInfo Object:

    -  updatedUserInfo
      Birthday null System.DateTime?
      City null string
      CountryDialCode 0 int
      CreatedBy 0 int
    +  CreatedDate {1/1/0001 12:00:00 AM} System.DateTime
      Email null string
      FullName null string
      HasAgreedTerms false bool
      IsEmailVerified false bool
      IsPhoneVerified true bool
      ModifiedBy 0 int
    +  ModifiedDate {1/1/0001 12:00:00 AM} System.DateTime
      Number null string
      UserId 1039 int

    Error again: An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code.

    Thanks for your help.

    Harsimrat


    • Edited by thukralz Monday, November 04, 2013 5:09 AM
    Monday, November 04, 2013 4:57 AM
  • Hi,

    I notice that in entity 'UpdateInfo' both the FullName(Name?) and the Email fileds are null. This may cause error.

    Have a try to set these fileds to be string.empty rather than null to see whether it will throw error again.

    Because in my test, if I set the update entity like:

    Order updateOrder = new Order() { OrderID = 4, OrderCode = "005", OrderName = string.Empty };
    It works fine. Hoeever, if I set the property 'OrderName' to be null or just ignore it. It will throw an error.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, November 04, 2013 7:03 AM
  • The problems I see with that approach is that I have to exactly know in advance; what I want to update, so that I can set all other properties to something else.

    So, there is no clean way of updating any single column in the table using LINQ ?

    Monday, November 04, 2013 7:10 AM
  • Also, by doing that; my table row got completely updated to new values.

    So, the workaround I see working here is that you get the object, make a copy; change what you need to and then send an update. That way whole row is taking an update at once. Essentially, to modify one field; we ended modifying whole row.

    Monday, November 04, 2013 7:16 AM
  • >>So, there is no clean way of updating any single column in the table using LINQ ?

    So you want to update one specify column.

    For this, please have a try with codes like below:

    using (DataBaseFirstDBEntities db = new DataBaseFirstDBEntities())
                {
                    Order updateOrder = new Order() { OrderID = 4, OrderCode = "005" };
    
                    db.Orders.Attach(updateOrder);
    
                    db.Entry<Order>(updateOrder).Property(o => o.OrderCode).IsModified = true;
    
                    try
                    {
                        db.Configuration.ValidateOnSaveEnabled = false;
                        db.SaveChanges();
                        db.Configuration.ValidateOnSaveEnabled = true;
                    }
                    catch (System.Data.Entity.Validation.DbEntityValidationException e)
                    { }
                }

    This is will only update the column 'OrderCode' with the exist record whose key value is 4.

    Before calling SaveChange(), we need to set db.Configuration.ValidateOnSaveEnabled to be false.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.



    Monday, November 04, 2013 7:40 AM