for*_*atc 2 c# asp.net linq-to-sql
我正在为一个项目编写DLL,我刚开始使用LINQ to SQL并将所有方法移动到这个新的dll之后.我发现我不能访问DataContext,因为它被处理掉了,我理解为什么但是我不确定如何查询我的主项目方法的结果如此:
我在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;
}
}
Run Code Online (Sandbox Code Playgroud)
打电话给:
IEnumerable<Problem> problems = ProblemsManipulation.GetProblemsNewest(10);
//Error can't acess it because it was disposed..
Run Code Online (Sandbox Code Playgroud)
这只是第一种方法,我有更大的方法所以我真的需要一种方法来做到这一点.必须有一种方法在DLL中使用LINQ to SQL?我知道我可以做一些像.ToList或者.ToArray然后我不能直接访问行属性,并且必须将它作为问题[0],问题[1]等引用,这比使用代码的语调更加混乱主要项目.
在使用using语句之后,将自动释放上下文,因此当实际枚举IEnumerable时,已经处理了上下文.
因此,您需要告诉Linq它应该继续并在您的using语句内部实际从数据库中检索值.你可以通过ToList()或ToArray(或其他人)这样做.
查看更新的代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2746 次 |
| 最近记录: |