Tag Archives: Entity Framework

Entity Framework – Attaching an entity of type failed because another entity of the same type already has the same primary key value

This happened to me while updating model from viewmodel and changing its State to Modified.
Before save, I wanted to check model property values existing in the database.
The solution is to use AsNoTracking() with your query. This way newly retrieved object won’t be tracked by the context. That means context will not recognize that the object has the same Id as a primary key value.

if (entity.CustomerID > 0)
{
	Customer existing =  _context.Set<Customer>().AsNoTracking().Where(c => c.CustomerID == entity.CustomerID).FirstOrDefault();
	entity.PasswordHash = existing.PasswordHash;
	entity.PasswordSalt = existing.PasswordSalt;
	entity.rowguid = existing.rowguid;
}

Entity Framework – Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.

This is how Visual Studio tells you that something went wrong while updating your entity.
Simple solution would be to catch System.Data.Entity.Validation.DbEntityValidationException and iterate through EntityValidationErrors collection.

try
{
	return _context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbvEx)
{
    List<string> errors = new List<string>();
    foreach (var validationErrors in dbvEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            errors.Add(string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage));
        }
    }
    return 0;
}

errors