I have an entity that needs history tracked on it for employee pay rates. The employeeRate object is:
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 to track history, when I "update" an employees rate, I retrieve all old records with their Id and set the ActiveFlag to false, then add a new entity with the new pay rate and the ActiveFlag set to 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 an Add operation on my DbContext object, the SQL being generated by EntityFramework is deleting all old records for that employee for some reason.
Generated SQL:
DELETE FROM
employeeratesWHEREEmployeeRateId= @p0;INSERT INTO
employeerates(ActiveFlag,CreateStamp,EmployeeId,LastModifiedBy,Rate,UpdateStamp) VALUES (@p1, @p2, @p3, @p4, @p5, @p6); SELECTEmployeeRateIdFROMemployeeratesWHERE ROW_COUNT() = 1 ANDEmployeeRateId=LAST_INSERT_ID();
Why would this be happening? Is there a way to keep EF from deleting these old records?
EDIT
I am using asp.net core and entity framework core.
newRate = _context.EmployeeRates.Add(newRate).Entity;... everything else looks fine. How doesBaseEntitylooks like? - MarcSaveChangestwice here? - stephen.vakil