【问题标题】:Linq DataContext - Where does it go in a class?Linq DataContext - 它在课堂上的什么位置?
【发布时间】:2013-01-28 19:17:44
【问题描述】:

我还是 LINQ 的新手,在知道将 DataContext 放在类中的什么位置时遇到了一些问题。

这是我尝试过的:

public class Student
{
    private static LinqClassesDataContext db = new LinqClassesDataContext();
    public static Profile GetProfile(int uID)
    {
        var profile = (from p in db.Profiles
                        where p.uID == uID
                        select p).FirstOrDefault();
        return profile;
    }
}

但我遇到了结果缓存问题(?) - 请参阅此问题:Weird caching issue with ASP.net/Linq

然后,我尝试将 DataContext 放在类中的每个方法中:

public class Student 
{
    public static Profile GetProfile(int uID)
    {
        using (LinqClassesDataContext db = new LinqClassesDataContext())
        {
            var profile = (from p in db.Profiles
                           where p.uID == uID
                           select p).FirstOrDefault();
            return profile;
        }
     }
}

但后来我的应用程序中出现“Dispose 后访问的 DataContext”错误。

所以,我见过的唯一其他方法就是这样:

public class Student 
{
    public static Profile GetProfile(int uID)
    {
        LinqClassesDataContext db = new LinqClassesDataContext();
        {
            var profile = (from p in db.Profiles
                           where p.uID == uID
                           select p).FirstOrDefault();
            return profile;
        }
     }
}

但这似乎不是最有效的方法。也许我错误地使用了 Linq(我是自学 ASP.net'er),但有人能告诉我前进的最佳方式吗?

【问题讨论】:

    标签: asp.net linq


    【解决方案1】:

    对象被附加到上下文中,所以一旦你处理它,如果你试图导航它的关系,你会得到这些类型的错误,就像你使用选项 #2 一样。

    由于 ASP.NET 是无状态的,因此您需要在每次需要时加载配置文件对象,而不是静态缓存对象,或者使用 LINQ to SQL 的 DataLoadOptions 对象加载对象及其所有相关数据(@ 987654321@)。这样,您在访问相关数据集时就不需要上下文。

    至于放在哪里,我总是把它放在HttpContext.Current.Items 集合中,它可以存储每个请求的实例,然后从这里共享给所有请求。我在它周围包装了一些代码,所以我的应用程序不知道它是从这里获取的。但是,您必须小心,因为如果 ASP.NET 之外的进程使用相同的代码,则这种方法会因为没有 HTTP 上下文而失败。在这种情况下,每次都实例化上下文。

    【讨论】:

      猜你喜欢
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多