[英]linq to sql Cannot access a disposed object. Returning a new created object
I am simply creating a new object that has one to on relationship. 我只是创建一个具有一对一关系的新对象。 A comment to a User relation.
对用户关系的评论。 When I try to retrieve the new object I get the error Cannot access a disposed object.
当我尝试检索新对象时,我收到错误无法访问已处置的对象。 I am not sure what is going on.
我不确定发生了什么。 Thanks for any help or suggestions.
感谢您的任何帮助或建议。
using (var db = new LinqEntityDataContext())
{
var comment = new Comment();
comment.CommentBy = GlobalVariables.User.ID;
comment.OutPutMessage = commentText.Trim();
comment.PhotoID = int.Parse(pictureID);
comment.CommentDate = DateTime.Now;
db.Comments.InsertOnSubmit(comment);
db.SubmitChanges();
return comment;
}
You need to set the return comment;
你需要设置
return comment;
after the last bracket. 在最后一个括号之后。
You are finishing the function just before the Dispose, that's why you get the Exception 您正在Dispose之前完成该功能,这就是您获得Exception的原因
Something like this. 像这样的东西。
var comment = new Comment();
using (var db = new LinqEntityDataContext())
{
comment.CommentBy = GlobalVariables.User.ID;
comment.OutPutMessage = commentText.Trim();
comment.PhotoID = int.Parse(pictureID);
comment.CommentDate = DateTime.Now;
db.Comments.InsertOnSubmit(comment);
db.SubmitChanges();
}
return comment;
So to understanding I guess with Linq to SQL you have to make two calls one to insert than another to get the data with the association. 因此,为了理解我认为使用Linq to SQL,您必须进行两次调用,而不是另一次调用以获取带有关联的数据。 So In my code I just have two using statements the second one just calling to get the object of the id created (seems redundant to me).
所以在我的代码中我只有两个using语句,第二个只是调用来获取id的对象(对我来说似乎是多余的)。 I hope that someone can post or direct this posting to a real solution.
我希望有人可以发布或指导这个帖子到真正的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.