实体框架(无法定义两个对象之间的关系)
我试图在 ASP .Net 网页中执行以下代码:
using (var wpe = new CL40215_wpnEntities())
{
int cid = Convert.ToInt32(cmbCity.SelectedItem.Value);
int catid = Convert.ToInt32(cmbCategory.SelectedValue);
Post p = new Post
{
title = txtTitle.Text,
description = txtDescription.Text,
User = u,
City = wpe.Cities.First(c => c.id == cid),
initialprice = 0,
finalprice = 10,
Category = wpe.Categories.First(c => c.id == catid),
postdate = DateTime.Now,
closedate = DateTime.Now.AddDays(Convert.ToInt32(cmbDays.SelectedValue)),
currentprice = 1
};
wpe.AddToPosts(p);
wpe.SaveChanges();
}
但是,我收到以下错误:
无法定义两个对象之间的关系,因为它们附加到不同的 ObjectContext 对象。
有谁知道为什么会发生这种情况以及如何解决这个问题?
I am trying to execute the following code in a ASP .Net web page:
using (var wpe = new CL40215_wpnEntities())
{
int cid = Convert.ToInt32(cmbCity.SelectedItem.Value);
int catid = Convert.ToInt32(cmbCategory.SelectedValue);
Post p = new Post
{
title = txtTitle.Text,
description = txtDescription.Text,
User = u,
City = wpe.Cities.First(c => c.id == cid),
initialprice = 0,
finalprice = 10,
Category = wpe.Categories.First(c => c.id == catid),
postdate = DateTime.Now,
closedate = DateTime.Now.AddDays(Convert.ToInt32(cmbDays.SelectedValue)),
currentprice = 1
};
wpe.AddToPosts(p);
wpe.SaveChanges();
}
However, I get the following error:
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
Does anyone have any idea why is this happening, and how to solve this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试更改对象初始化以首先附加帖子对象,然后创建关系。
如果您使用持久性感知类,则它们需要在创建关系之前相互了解。这意味着您需要在构建对象之前分离子对象,然后首先附加所有子对象,或者如上所述,首先附加新帖子。不确定您的 addtoposts 存储库调用正在做什么,但如果您在对象有效之前没有运行保存更改,那么这应该可以工作。
编辑:抱歉。我没有注意到添加了用户对象。您需要使用当前上下文重新加载用户,或者将用户从之前的上下文中分离出来并将其附加到当前上下文。
Try changing your object initialisation to attach the post object first then create the relationship.
If you are using persistence aware classes, they need to know about each other before the relationship can be created. That means you will either need to detach the children before building the object, then attach them all children first, or, as above, attach the new post first. Not sure what youre addtoposts repo call is doing, but that should work provided you aren't running a save changes before the object is valid.
EDIT: Apologies. I didn't notice the user object being added. You will need to either reload the user with the current context or DETACH the user from it's previous context and ATTACH it to the current one.
可能的问题之一是
u
引用了User
。我不知道它来自哪里,而且u
确实有可能来自不同的上下文。One of the possible problems is
u
referring toUser
. I don't see where it comes from and it indeed could be possible thatu
comes from a different context.