0

假设以下方法存在于 WCF 服务中。UI 检索到 Status 对象的实例,并使用此方法对服务进行后续调用。它没有像我期望的那样将状态分配给用户,而是尝试插入状态。我究竟做错了什么?

void Method(Status status)
{
    //not sure if this is even needed, the status never changed
    context.Statuses.ApplyChanges(status);

    //get the first user from the database
    User user = context.Users.Where(u => u.Id = 1).First();

    //set user status to some existing status
    user.Status = status;

    //this throws an exception due to EF trying to insert a new entry
    //into the status table, rather than updating the user.StatusId column.
    context.SaveChanges();
}
4

3 回答 3

1

试试这个:

        using (Entities ctx = new Entities())
        {
            ctx.Statuses.Attach(status);

            ObjectStateEntry entry = ctx.ObjectStateManager.GetObjectStateEntry(status);
            entry.ChangeState(EntityState.Modified);

            //get the first user from the database
            User user = ctx.Users.Where(u => u.Id = 1);

            //set user status to some existing status
            user.StatusID = status.StatusID;

            ctx.SaveChanges();
        }

如果您有兴趣,这里有一个关于 CRUD 和 Entity Framework 的教程。

于 2011-04-11T19:45:59.757 回答
1

问题是您正在使用附加用户。当 STE 附加到上下文时,它的行为方式与任何其他实体完全相同。更何况它的自我跟踪机制没有被激活。因此,您必须先将状态附加到上下文,然后再将其设置给用户,否则它将被跟踪为必须插入的新实体:

void Method(Status status)
{
    User user = context.Users.Where(u => u.Id = 1).First();

    context.Attach(status);
    user.Status = status;

    context.SaveChanges();
}
于 2011-04-11T21:05:00.093 回答
0

必须写一个答案,因为我还不能评论另一个答案(rep score < 50)[这有点奇怪,但我明白为什么会这样]因为我想为@Ladislav的答案增加一些清晰度。

Status从 WCF 调用传入的对象与context您用于查找对象的User对象不同,因此跟踪代码未与该上下文相关联。这就是为什么附加它可以让您保存分配而无需context考虑status需要插入数据库的新实体。

于 2011-05-03T18:54:00.170 回答