实体框架:附加实体不保存

时间:2010-05-05 19:06:59

标签: entity-framework

我无法弄清楚为什么在以下代码上调用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查询,因此没有保存任何附加对象。

3 个答案:

答案 0 :(得分:3)

他们没有保存,因为您在附加实体之前更改了实体。上下文(通常)跟踪更改,因此不会跟踪对分离实体的更改。因此,没有什么可以保存。

答案 1 :(得分:0)

离开我的头顶后,你不应该从帐户中删除角色后执行SaveChanges()吗?您是不是只是删除附加到用户的角色,然后重新附加相同的角色?既然它保存了变化,那么它不会有任何改变吗?

答案 2 :(得分:0)

有时这是因为实体对象在分离时被修改了。帖子here将展示如何清除它。

相关问题