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!