EF 4.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();
}
Let's assume that the below method lives in a WCF service. The UI retrieved an instance of the Status object, and makes a subsequent call to the service using this method. Instead of assigning the status to the user as I would expect, it attempts to insert the status. What am I doing wrong?
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是您正在与附加用户一起工作。当 STE 附加到上下文时,它的行为方式与任何其他实体完全相同。而且它的自我跟踪机制没有被激活。因此,在将状态设置给用户之前,您必须将状态附加到上下文,否则它将被作为必须插入的新实体进行跟踪:
The problem is that you are working with attached user. When the STE is attached to the context it behaves exactly in the same way as any other entity. More over its self tracking mechanism is not activated. So you must attach the status to the context before you set it to the user or it will be tracked as a new entity which has to be inserted:
试试这个:
这是关于使用实体框架进行 CRUD 的教程如果你有兴趣的话。
Try this instead:
Here's a tutorial on CRUD with Entity Framework if you're interested.
必须写一个答案,因为我还不能评论另一个答案(代表分数 < 50)[有些奇怪的不对劲,但我明白为什么会这样]因为我想添加@Ladislav 的回答有些清晰。
来自 WCF 调用的
Status
对象并非来自您用于查找User
对象的同一个context
,因此跟踪代码不符合该上下文。这就是为什么附加它可以让您保存作业,而无需context
认为status
是需要插入数据库的新实体。Have to write an answer because I can't yet comment on another answer (rep score < 50) [something weirdly not right about that, but I get why it's like that] because I wanted to add some clarity to @Ladislav's answer.
The
Status
object coming in from the WCF call did not come from the samecontext
you are using to find theUser
object, so the tracking code is not fixed up with that context. This is why attaching it will allow you to save the assignment without thecontext
thinking thatstatus
is a new entity requiring an insert into the database.