Linq2Sql:将实体重新附加到数据上下文,但不是原始数据上下文问题
有人可以帮忙吗?我有一个 linq2sql 问题,并尝试通过数据上下文附加(更新)实体类,它抱怨它不是原始上下文,这是真的(参见下面的代码)...我认为打开数据上下文是最佳实践,并且不需要的时候关闭?
我基本上让我的应用程序调用一个服务层,该服务层又调用一个数据库上下文所在的存储库...您可以在这里看到我有 2 个数据上下文,每个方法中都定义了一个数据上下文...
基本上发生的事情是我的应用程序“获取”预订...然后应用程序更新实体类“预订”,然后将其重新发送到“更新”预订..任何人都可以帮忙..我完全被困在这里
基本上是我的代码
public bool UpdateReservation(Reservation reservation)
{
bool success = false;
try
{
ResDataContext db = new ResDataContext ();
db.Reservations.Attach(reservation);
db.SubmitChanges();
success = true;
}
catch (Exception ex)
{
Console.WriteLine("");
}
return success;
}
public Reservation GetReservation(string reservationNumber)
{
ResDataContext db = new ResDataContext ();
return db.Reservations.Where(r => r.ReservationNumber == reservationNumber).SingleOrDefault();
}
can anyone help? I have an issue with linq2sql and trying to Attach (update) an entity class through a datacontext, it complains its not the original context, this is true (see code below) ... I thought it was best practices to open the datacontext and close it when not needed?
I basically have my app calling a service layer which in turn calls a repository where the db context is.... You can see here i have 2 data contexts, well a datacontext is defined in each method...
Basically what happens is my app "Gets" a reservation ... then the app updates the entity class "Reservation" and then resends it to "Updates" a Reservation.. Can anyone help.. I am completely stuck
here is basicallly my code
public bool UpdateReservation(Reservation reservation)
{
bool success = false;
try
{
ResDataContext db = new ResDataContext ();
db.Reservations.Attach(reservation);
db.SubmitChanges();
success = true;
}
catch (Exception ex)
{
Console.WriteLine("");
}
return success;
}
public Reservation GetReservation(string reservationNumber)
{
ResDataContext db = new ResDataContext ();
return db.Reservations.Where(r => r.ReservationNumber == reservationNumber).SingleOrDefault();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您没有重新附加到相同的数据上下文。
您需要在调用之间保持 ResDataContext 处于活动状态。
这是 Eniity Framework(不是 linq to SQL),但问题类似:
实体框架: AttachAsModified 失败/混乱:)
The problem is that you are not reattaching to the same data context.
You need to keep the ResDataContext alive between the calls.
This was Eniity Framework (not linq to SQL), but the problem was similar:
Entity Framework: AttachAsModified failure / confusion :)
您可以首先从 DataContext 收集正确的 Reservation 对象,然后更新并提交它。
像这样:
You could first collect the correct Reservation object from the DataContext and then update and submit it.
Like this: