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

问题描述:

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

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

+0

都怎么样'usr中。[UpdateTimeProperty] = [updatedDateTimevalue] '?我不知道你想用更新的时间戳更新哪个属性。 –

+0

您是否想在“更新”表中添加新记录以保留历史记录或只更新“更新日期”。如果后者为什么你有一个额外的表来存储'更新日期'? – Scrobi

+0

@Scrobi User和Update表之间似乎存在一对一的关系。如果这是完整的表格结构而不是更大图片的一部分,则没有意义。它可以只是一个列而已。 – Harsh

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

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

当第一次注册数据时,我使用 'User akun = new User(); akun.NAME = textBox1.Text; akun.PASSWORD = textBox2.Text; akun.DateCreate = DateTime.Now; entities.Users.Add(akun); entities.SaveChanges();' 在表的用户, ID = 1个 名称=安迪 密码= Andy123 DateCreate = 2017年10月11日 UpdateId = NULL RecoveryId = NULL 表更新 ID = NULL DateOfUpdate = NULL 表恢复 ID = NULL DateOfRecovery = NULL –

+0

这是因为你必须添加一个条目到'Update'表中。在第一次更新或者'用户'被创建/首次注册时,你想在什么时候向该表添加条目? – Scrobi

+0

我想在第一次更新时, 或者你有什么建议? –