0

I have a problem when I update entity in EF6. The code looks like this:

public PICCOSSourceCost GetCOSSourceCost(int sourceCostID)
{
    return ERPContext.PICCOSSourceCost.Where(sc => sc.ID == sourceCostID && !sc.Deleted).FirstOrDefault();
}
public PICCOSSourceCost UpdateCOSSourceCost(PICCOSSourceCost sourceCost, bool saveChanges = true)
{
    var sc = GetCOSSourceCost(sourceCost.ID);
    if (sc == null)
    {
        throw new PICObjectNotFoundException<PICCOSSourceCost>(sourceCost, new List<string>()
        {
            nameof(PICCOSSourceCost.PICCOSSourceID),
            nameof(PICCOSSourceCost.PICCOSPriceTypeID),
            nameof(PICCOSSourceCost.Price),
            nameof(PICCOSSourceCost.EffectiveDate)
        });
    }

    sc.PICCOSSourceID = sourceCost.PICCOSSourceID;
    sc.PICCOSPriceTypeID = sourceCost.PICCOSPriceTypeID;
    sc.Price = sourceCost.Price;
    sc.EffectiveDate = sourceCost.EffectiveDate;
    sc.Deleted = sourceCost.Deleted;
    sc.CreatedBy = sourceCost.CreatedBy;
    sc.CreatedDate = sourceCost.CreatedDate;
    sc.LastModifiedBy = sourceCost.LastModifiedBy;
    sc.LastModifiedDate = sourceCost.LastModifiedDate;

    if (saveChanges) ERPContext.SaveChanges();

    return sc;
}

As you can see that the "GetCOSSourceCost" method get entity from EF. And the first parameter "sourceCost" in the "UpdateCOSSourceCost" method is passed in from FrontEnd, which is also got from EF6. When I debug the code, there is an "System.Data.Entity.Validation.DbEntityValidationException" occurred. I don't know why. I think that it should be okay because I just get an entity object and just change its properties and save changes. Is it because there are two references to the same object? If I remove the property assignment code, the error will disappear.

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

Do you know why it throws this exception? Please help me. Thank you so much!

Jeffery You
  • 109
  • 2
  • 2
  • 11
  • 1
    What does `Exception.EntityValidationErrors` contain? – Minijack May 22 '19 at 03:40
  • It might help if you post your Entity and the Model binding – Minijack May 22 '19 at 03:41
  • I use DB First to create EF models, and add entities into the model. I think "EntityValidationErrors" is just a message which means an error occurs when validating entities. the real exception type is "System.Data.Entity.Validation.DbEntityValidationException" – Jeffery You May 22 '19 at 03:53
  • Have you tried removing the property assignment lines and adding them back one by one? – mcalex May 22 '19 at 03:55
  • @JefferyYou When the Exception is thrown, you should be able to inspect it (dependent on IDE), if not you can catch the exception `try { ... } catch (Exception ex) { Debugger.Break(); }` and then inspect the variable, which should contain a property called "EntityValidationErrors". – Minijack May 22 '19 at 04:00
  • I appreciate your answer very much. I have found the root cause of the error by the link [link](https://stackoverflow.com/questions/7795300/validation-failed-for-one-or-more-entities-see-entityvalidationerrors-propert). The root cause is that some required fields is NULL... Thank you so much. – Jeffery You May 22 '19 at 04:13

2 Answers2

1

Based on this

http://mattrandle.me/viewing-entityvalidationerrors-in-visual-studio/

You can use is a special debugger variable- $exception

To view the EntityValidationErrors collection you can use below to show watch windows

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32
0

Thank you for your help so much. I have solved my issue by the following link: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details For the sake of this link, I debugged and find the root cause of the entity validation error. Some required fields are set to NULL value. The code from the answer is very useful:

try
{
    // Your code...
    // Could also be before try if you know the exception occurs in SaveChanges
    context.SaveChanges();
}
catch (DbEntityValidationException e)
{
    foreach (var eve in e.EntityValidationErrors)
    {
        Console.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)
        {
            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
        }
    }
    throw;
}
Jeffery You
  • 109
  • 2
  • 2
  • 11