LINQ到DataContext的处置后的SQL查询使用 [英] LINQ to SQL use query after DataContext Dispose

查看:130
本文介绍了LINQ到DataContext的处置后的SQL查询使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的DLL一个项目,我刚开始使用LINQ to SQL和移动的所有方法这个新的DLL后。我disovered因为它的​​处置,我不能接取的DataContext,我明白为什么,但我不知道我怎么能接取查询结果我的主要项目方法,因此:

Im writing DLL for one project, I just started using LINQ to SQL and after moving all methods to this new dll. I disovered that I can't acess DataContext because it was disposed, I understand why but I'm not sure how I can acess results of query for my main project method so:

我的DLL方法

 public static IEnumerable<Problem> GetProblemsNewest(int howMuch)
        {
            using (ProblemClassesDataContext context = new ProblemClassesDataContext())
            {
                var problems = (from p in context.Problems orderby p.DateTimeCreated select p).Take(howMuch);

                return problems;
            }
        }

调用它:

IEnumerable<Problem> problems = ProblemsManipulation.GetProblemsNewest(10);
//Error can't acess it because it was disposed..

这仅仅是第一种方法,我有较大的所以我真的需要一种方法来做到这一点。必须有使用LINQ的DLL到SQL的方式?我知道我可以这样做 .ToList .ToArray 但后来我就没法接取行属性直接将不得不引用它的问题[0],问题[1]等,这甚至比在主要项目有code的语气较为凌乱。

This is just first method, I have larger ones so I really need a way to do this. There must be a way to use LINQ to SQL in DLL? I know I can do something Like .ToList or .ToArray but then I wouldn't be able to acess row properties directly and would have to reference it as problem[0],problem[1] etc. which is even more messy than having tone of code in main project.

推荐答案

你是using语句的上下文中自动处理外之后,所以当IEnumerable的实际列举的上下文中已经部署。

After you are outside of the using statement the context is automatically disposed, so when the IEnumerable is actually enumerated the context is already disposed.

因此​​,你需要告诉LINQ的,它应该继续和实际,而你的使用语句内检索数据库中的值。您可以通过了ToList这样做()的ToArray (或其他)。

Therefore you need to tell Linq that it should go ahead and actually retrieve the values from the DB while your inside of your using statement. You can do so via ToList() or ToArray (or others).

请参阅更新code:

public static IList<Problem> GetProblemsNewest(int howMuch)
{
    using (ProblemClassesDataContext context = new ProblemClassesDataContext())
    {
        var problems = (from p in context.Problems orderby p.DateTimeCreated select p).Take(howMuch);

        return problems.ToList();
    }
}

这篇关于LINQ到DataContext的处置后的SQL查询使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆