History in database using entity framework

本小妞迷上赌 提交于 2019-12-13 02:13:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/6689291/history-in-database-using-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!