我想不通,爲什麼在不改變的對象我重視的SaveChanges調用()以下代碼結果:實體框架:附加實體沒有保存
public void Update()
{
AccountUser accountUser = new AccountUser();
// update
using (var db = new MedicalSystemDBEntity())
{
var query = from user in db.AccountUsers
where user.id == this.UserID
select user;
if (query.Count() > 0)
{
accountUser = query.First();
accountUser.AccountRoles.Load();
accountUser.SecurityNavigationNodes.Load();
// delete existing user roles before re-attaching
if (accountUser.AccountRoles.Count > 0)
{
foreach (AccountRole role in accountUser.AccountRoles.ToList())
{
accountUser.AccountRoles.Remove(role);
}
}
db.SaveChanges();
// get roles to add
List<int> roleIDs = new List<int>();
foreach (UserRole r in this.AccountRoles)
{
roleIDs.Add(r.RoleID);
}
var roleEntities = from roles in db.AccountRoles
where roleIDs.Contains(roles.id)
select roles;
accountUser.AccountRoles.Attach(roleEntities);
accountUser.username = this.Username;
accountUser.firstname = this.FirstName;
accountUser.middlename = this.MiddleName;
accountUser.lastname = this.LastName;
accountUser.enabled = this.Enabled;
if (this.LastActivityDate != null || this.LastActivityDate != DateTime.MinValue)
accountUser.lastactivitydate = this.LastActivityDate;
db.SaveChanges();
}
}
}
在調試程序,我看到正在加載正確的roleEntities,並且它們是有效的對象。但是,如果我使用SQL事件探查器,則看不到UPDATE或INSERT查詢,結果沒有保存我的連接對象。
記住我不是想添加一個新用戶,我也不想添加一個新的帳戶角色......我只想將accountUser與一組新的AccountRoles相關聯(這裏有一個多對多的帳戶) AccountRoles和AccountUsers之間通過連接表有很多關係) – 2010-05-05 19:19:34
在你的例子中,請指定你的上下文範圍和生命週期。例如。通過定義「using()...」塊。您使用'accountUser',但我們無法知道該對象正在發生什麼。另外,儘量不要在代碼片段中使用'var':) – kervin 2010-05-05 19:25:34
Kervin:我現在已經添加了一個更大的代碼示例:)這是我的第一個Stackoverflow文章,非常抱歉。 – 2010-05-05 19:29:28