我想不通,为什么在不改变的对象我重视的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