使用实体框架的数据库历史记录
我想将历史记录存储在我的表中。
我有表Employee
。
Employee
{
[Id],
[name],
[phone],
[isActive],
[createdDate],
[closedDate](default '23:59:59 9999-12-31'),
[DepartmentId] References Department(id)
}
当 Employee
更改时,我通过 Id
检索原始值并执行 isActive=False, returnedDate=DateTime.Now
,然后将修改后的值保存为修改原始值的新Employee
。
void UpdateEmployee(Employee employee)
{
ContextDB db=new ContextDB();
var employeeToUpdate=db.Employees.Find(it=>it.Id==employee.Id);
employeeToUpdate.isActive=false;
employeeToUpdate.closeDate=DateTime.Now;
var newEmployee=new Employee
{
Name=employee.Name,
Phone=employee.Phone,
....
}
db.Employees.AddObject(newEmployee);
// How I can do this with EF
db.Employees.Modify(employeeToUpdate);
db.SaveChanges();
}
我该怎么做?还有一个问题,如果我引用另一个表“Department”并且还希望在此表中存储历史记录,我需要做什么。如果Employee
对象中的Department
发生变化,我该怎么办。
PS 我使用自我跟踪实体。
I want to store history in my table.
I have table Employee
.
Employee
{
[Id],
[name],
[phone],
[isActive],
[createdDate],
[closedDate](default '23:59:59 9999-12-31'),
[DepartmentId] References Department(id)
}
When Employee
is changed, I retrieve original values by Id
and do isActive=False, closedDate=DateTime.Now
and then I save modified value as new Employee
with modified original values.
void UpdateEmployee(Employee employee)
{
ContextDB db=new ContextDB();
var employeeToUpdate=db.Employees.Find(it=>it.Id==employee.Id);
employeeToUpdate.isActive=false;
employeeToUpdate.closeDate=DateTime.Now;
var newEmployee=new Employee
{
Name=employee.Name,
Phone=employee.Phone,
....
}
db.Employees.AddObject(newEmployee);
// How I can do this with EF
db.Employees.Modify(employeeToUpdate);
db.SaveChanges();
}
How can I do this? And another question, what I need do if I have reference to another table Department
and also want store history in this table. How should I do if changes Department
in Employee
object.
P.S. I use Self-Tracking Entities.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它应该可以简单地工作而无需调用任何
Modify
。您从数据库加载了实体,并在将其附加到上下文时修改了其字段,因此上下文应该知道更改并将它们保存到数据库中。我发现您的架构非常糟糕的是,对员工的每次更改都会导致活动记录具有另一个
Id
。因此,如果您正在使用员工表并与之建立关系,外键将不再指向活动记录。如果您想这样做,则不应为活动记录创建新记录,而应为停用记录创建新记录。It should simply work without calling any
Modify
. You loaded entity from the database and you modified its fields while it is attached to the context so the context should know about changes and persist them to the database.What I find totally bad about your architecture is that each change to your employee will result in active record with another
Id
. So if you are using and relation with employee table, foreign keys will not point to active record any more. If you want to do it this way you should not create a new record for active record but you should instead create a new record for deactivated record.