【发布时间】:2011-04-11 19:38:54
【问题描述】:
假设以下方法存在于 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();
}
【问题讨论】:
-
是的,模式明智的用户有一个外键 User.StatusId,因此分配了 user.Status = status;
-
我假设您发布的代码不是真正的代码,因为您的检索代码实际上并未运行查询。您需要在 where 子句之后添加
.First()(或Single()或任何您想要的)以实际检索用户实例。 -
对不起,这就是我在记事本中输入示例所得到的。谢谢 KallDrexx。
标签: c# asp.net entity-framework entity-framework-4 self-tracking-entities