开发者

History in database using entity framework

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(ne开发者_开发问答wEmployee);

    // 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜