I have an organization that needs a history tracked on it to pay employees. EmployeeRate object:
public class EmployeeRate : BaseEntity { [Key] public int EmployeeRateId { get; set; } public int EmployeeId { get; set; } public double Rate { get; set; } } public class BaseEntity { public bool ActiveFlag { get; set; } public DateTime CreateStamp { get; set; } public DateTime UpdateStamp { get; set; } public string LastModifiedBy { get; set; } }
So, in order to keep track of the history, when I “update” the level of employees, I retrieve all the old records with their identifier and set the ActiveFlag value to false, and then add a new object with a new payment rate, and the ActiveFlag value is true. Here is my function for this operation:
private EmployeeRate UpdateRate(EmployeeRate model, string currentUser) { var existingRates = _context.EmployeeRates.Where(r => r.EmployeeId == model.EmployeeId).ToList(); foreach(var rate in existingRates) { rate.ActiveFlag = false; rate.UpdateStamp = DateTime.UtcNow; rate.LastModifiedBy = currentUser; } _context.SaveChanges(); var newRate = new EmployeeRate() { EmployeeId = model.EmployeeId, Rate = model.Rate, ActiveFlag = true, CreateStamp = DateTime.UtcNow, UpdateStamp = DateTime.UtcNow, LastModifiedBy = currentUser }; newRate = _context.EmployeeRates.Add(newRate).Entity; _context.SaveChanges(); return newRate; }
When I do the Add operation on my DbContext, the SQL generated by EntityFramework for some reason deletes all the old records for this employee.
Generated SQL:
REMOVE FROM employeerates WHERE EmployeeRateId = @ p0;
ActiveFlag employeerates ( ActiveFlag , CreateStamp , EmployeeId , LastModifiedBy , Rate , UpdateStamp ) VALUES (@ p1, @ p2, @ p3, @ p4, @ p5, @ p6); SELECT EmployeeRateId FROM employeerates WHERE ROW_COUNT () = 1 AND EmployeeRateId = LAST_INSERT_ID ();
Why is this happening? Is there a way to keep EF from deleting these old entries?
EDIT
I use asp.net core core and entity core.