Linq 为什么dbcontext在foreach循环之前被释放
我一直在努力弄清楚为什么这段代码在foreach循环之前处理dbcontext。任何线索都将不胜感激。谢谢Linq 为什么dbcontext在foreach循环之前被释放,linq,entity-framework-5,using,Linq,Entity Framework 5,Using,我一直在努力弄清楚为什么这段代码在foreach循环之前处理dbcontext。任何线索都将不胜感激。谢谢 [TestMethod] public void CreatePostAddComment() { IQueryable<Post> thePost; using (var _context = new BlogRepository()) { _context.AddPost(Get
[TestMethod]
public void CreatePostAddComment()
{
IQueryable<Post> thePost;
using (var _context = new BlogRepository())
{
_context.AddPost(GetTestPost());
var retrivePost = _context.GetPostByName("TestPost1");
thePost = retrivePost;
}
foreach (var post in thePost)
{
using (var _dbContext = new BlogRepository())
{
_dbContext.AddComment(GetTestComment(post));
}
}
}
[TestMethod]
public void CreatePostAddComment()
{
我可以阅读这篇文章;
使用(var\u context=new blog repository())
{
_AddPost(GetTestPost());
var retrievepost=_context.GetPostByName(“TestPost1”);
帖子=检索帖子;
}
foreach(邮件中的var post)
{
使用(var _dbContext=new BlogRepository())
{
_AddComment(GetTestComment(post));
}
}
}
using语句实际上是语法糖,它等价于:-
[TestMethod]
public void CreatePostAddComment()
{
IQueryable<Post> thePost;
{
var _context = new BlogRepository();
_context.AddPost(GetTestPost());
var retrivePost = _context.GetPostByName("TestPost1");
thePost = retrivePost;
_context.Dispose();
//Note, using is much better, because Dipose is called
//even if there is an exception.
}
foreach (var post in thePost)
{
using (var _dbContext = new BlogRepository())
{
_dbContext.AddComment(GetTestComment(post));
}
}
}
使用将在其块的末尾处理上下文。我知道,但IQueryable thePost是否仍应在foreach中的作用域中?否。不会因为您已在其作用域之外声明变量而延迟处理。谢谢提供的信息。从您的示例中,我必须做的唯一不同的事情是GetPostByName和GetTestComment在存储库中各自的方法中调用了SaveChanges。我强烈建议不要在域代码(如GetTestPost和GetPostByName)中调用SaveChanges。它会将您永远绑定到EntityFramework。您的域代码应该与存储库的实现无关。如果要测试域代码,可以将存储库更改为一个列表。另外,实现一个存储库模式。
[Rollback]
[TestMethod]
public void CreatePostAddComment()
{
using(var _context = new BlogRepository())
{
_context.AddPost(GetTestPost());
_context.SaveChanges();
var thePost = _context.Posts.First(x => x.Name =="TestPost1");
_dbContext.AddComment(GetTestComment(post));
_context.SaveChanges();
}
}