【问题标题】:How To insert date when you update the password?如何在更新密码时插入日期?
【发布时间】:2017-08-11 07:18:20
【问题描述】:

您可以查看我的图片: 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();

所以,当我更新密码时,如何让我的更新时间也输入

【问题讨论】:

  • usr.[UpdateTimeProperty] = [updatedDateTimevalue] 怎么样?我不知道您要使用更新的时间戳更新哪个属性。
  • 您是想在Update 表中添加一条新记录以保留历史记录,还是只是更新Date of Update。如果是后者,为什么还要另外一个表来存储Date of Update
  • @Scrobi User 和 Update 表之间似乎存在一对一的关系。如果这是完整的表结构而不是更大图景的一部分,那就没有意义了。它可以只是一个列。
  • @Scrobi : 我想保存更新时间,当用户更新密码时,时间会根据 datetime.now 改变,例如:A:修改密码 xxx 变成 xYz,自动更新表会保存时间 A 将密码更改为 11-10-2017 (dd-mm-yyyy) A: 那么明天 A 将其密码从 xYz 更改为 123,自动更新表将节省时间 A 将密码更改为 12-10-2017 (dd-mm -yyyy)

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


【解决方案1】:

您可以覆盖 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 覆盖将是通用的,并且适用于从该基类继承的所有表。

【讨论】:

    【解决方案2】:

    如果您只需要更新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();
    

    【讨论】:

    • 第一次注册数据时,我使用User akun = new User(); akun.NAME = textBox1.Text; akun.PASSWORD = textBox2.Text; akun.DateCreate = DateTime.Now; entities.Users.Add(akun); entities.SaveChanges();在表用户中,ID = 1 Name = Andy Password = Andy123 DateCreate = 10-11-2017 UpdateId = NULL RecoveryId = NULL Table Update ID = NULL DateOfUpdate = NULL 表恢复 ID = NULL DateOfRecovery = NULL
    • 那是因为您必须在Update 表中添加一个条目。首次更新或创建/首次注册 user 时,您希望在什么时候向此表添加条目?
    • 我想要第一次更新的时候,或者你有什么建议?
    • 然后你需要检查Update是否为空,是否创建一个新对象。您还必须将联接更改为左联接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-02
    • 2020-10-25
    • 2011-05-31
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 2013-08-12
    相关资源
    最近更新 更多