我有一個模型,稱爲用戶(從我的數據庫派生),我在部分類中添加方法,允許用戶對象執行維護類型的工作。如何將EntityFramework模型保存在其內部?
舉個例子,我想我的應用程序與其他數據庫更新用戶的SupervisorID在其數據庫中比對:
public partial class User
{
DatabaseEntities db = new DatabaseEntities();
OtherEntities otherDB = new CommonEntities();
public void UpdateSupervisor()
{
// Lookup the Supervisor's Username in the other Database:
string supervisorUsername = (from x in otherDB.vwEmployees
join y in otherDB.vwEmployees on x.Supervisor_EID equals y.Employee_ID
where x.User_ID == searchUsername
select y.User_ID).FirstOrDefault();
// Update the database to record the Supervisor of this staff member:
this.SupervisorUserID = (from x in db.Users
where x.ADUsername == supervisorUsername
select x.UserID).FirstOrDefault();
// At this point, this.SupervisorUserID stores the correct int, but the following command doesn't save any changes.
db.SaveChanges();
}
}
代碼工作,除了db.SaveChanges()不保存任何事情(沒有錯誤)。
的方法被稱爲這個類的外部,作爲登錄處理的一部分:
public class Login {
// Connect to the database:
DatabaseEntities db = new DatabaseEntities();
User currentUser = new User();
// Do some stuff...
// Update the user's supervisor:
currentUser.UpdateSupervisor();
}
任何想法?
感謝,
羅素
是'DatabaseEntities'與'db'一樣的''實例嗎?否則,它不會檢測到任何更改,因爲'db'僅用於在您發佈的代碼中獲取數據。如果使用另一個實例接收到'this',它將不起作用。 –
更新了問題 - 我希望它更清楚。 :-) –