如何在更新密码时插入日期?

时间:2017-08-11 07:18:21

标签: c# sql-server entity-framework ado.net linq-to-entities

你可以查看我的图片: My relationship picture

        entities = new sampleEntities();
        User usr = (from i in entities.Users
                    join j in entities.Updates
                    on i.ID equals j.ID
                    where i.NAME == name
                    select i).First();

        usr.PASSWORD = textBox2.Text;
        entities.SaveChanges();

所以,当我更新密码时,如何进入更新时间

2 个答案:

答案 0 :(得分:2)

您可以覆盖saveChanges。

public override int SaveChanges()
{

    var addedUsers = ChangeTracker.Entries<User>().Where(x => x.State 
                                       == EntityState.Added).ToList();

    addedUsers.ForEach(x => 
    {
        x.Update = new Update{DateOfUpdate = DateTime.Now}
    });

    var modifiedUsers = ChangeTracker.Entries<User>().Where(x => x.State 
                                           == EntityState.Modified).ToList();

    modifiedUsers.ForEach(x => 
    {
        x.Update.DateOfUpdate = DateTime.Now;
    });

    return base.SaveChanges();
}

如果您打算跟踪多个表的这些修改日期,最好使用具有这些日期的基类,并继承此类中需要修改日期的所有表。这样你的saveChanges覆盖将是通用的,适用于从该基类继承的所有表。

答案 1 :(得分:0)

如果您只需要更新Date of Update,则可以更改选择以恢复此数据,然后同时更新UserUpdate

entities = new sampleEntities();
var data = (from i in entities.Users
                join j in entities.Updates
                on i.ID equals j.ID
                where i.NAME == name
                select new {user = i, update = j).First();

    data.user.PASSWORD = textBox2.Text;
    if (data.update == null) data.update = new Update();

    data.update.DateofUpdate = DateTime.Now;
    entities.SaveChanges();