2017-08-11 76 views
2

您可以查看我的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

回答

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覆蓋將是通用的,並適用於從該基類繼承的所有表。

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(); 
+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

我想在第一次更新時, 或者你有什麼建議? –