帮助我理解我的“Using”和“DataContext”

发布于 2024-08-05 07:51:17 字数 1685 浏览 5 评论 0原文

有人可以向我解释一下以下内容吗?第一个是我如何调用该方法,第二个是 LINQ 方法。

我的好奇心源于这样一个事实:如果我取消注释 using 部分,我会收到 context 错误。

为什么?我显然不完全理解使用上下文。我想更好地理解这一点。

Guid workerID = new Guid(new ConnectDAL.DAL.Security().GetUserIDByUserLogin(HUD.CurrentUser));

        var myMembers = BLLCmo.GetAllMembers(workerID);
        if (myMembers.Rows.Count != 0)
        {
            dgvMyMembers.DataSource = myMembers;
        }
        else
        {
            var allMembers = BLLCmo.GetAllMembers();
            dgvMyMembers.DataSource = allMembers;
        }




    internal static CmoDataContext context = new CmoDataContext();

    public static DataTable GetAllMembers()
    {
        DataTable dataTable;

        //using (context)
        //{
            var AllEnrollees = from enrollment in context.tblCMOEnrollments
                               select new
                                       {
                                           enrollment.ADRCReferralID,
                                           enrollment.ClientID,
                                           enrollment.CMONurseID,
                                           enrollment.CMOSocialWorkerID,
                                           enrollment.DisenrollmentDate,
                                           enrollment.DisenrollmentReasonID,
                                           enrollment.EconomicSupportWorkerID,
                                           enrollment.EnrollmentDate
                                       };

            dataTable = AllEnrollees.CopyLinqToDataTable();
        //}
        return dataTable;
    }

Can someone please explain the below to me. First is how I call the method and the second bit is the LINQ Method.

My curiousity stems from the fact that I get a context error if I un-comment the using portion.

Why? I apparently do not fully understand using and context's. And I would like to better understand this.

Guid workerID = new Guid(new ConnectDAL.DAL.Security().GetUserIDByUserLogin(HUD.CurrentUser));

        var myMembers = BLLCmo.GetAllMembers(workerID);
        if (myMembers.Rows.Count != 0)
        {
            dgvMyMembers.DataSource = myMembers;
        }
        else
        {
            var allMembers = BLLCmo.GetAllMembers();
            dgvMyMembers.DataSource = allMembers;
        }




    internal static CmoDataContext context = new CmoDataContext();

    public static DataTable GetAllMembers()
    {
        DataTable dataTable;

        //using (context)
        //{
            var AllEnrollees = from enrollment in context.tblCMOEnrollments
                               select new
                                       {
                                           enrollment.ADRCReferralID,
                                           enrollment.ClientID,
                                           enrollment.CMONurseID,
                                           enrollment.CMOSocialWorkerID,
                                           enrollment.DisenrollmentDate,
                                           enrollment.DisenrollmentReasonID,
                                           enrollment.EconomicSupportWorkerID,
                                           enrollment.EnrollmentDate
                                       };

            dataTable = AllEnrollees.CopyLinqToDataTable();
        //}
        return dataTable;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

⒈起吃苦の倖褔 2024-08-12 07:51:17

“使用”块会自动处理您正在使用的对象。由于您没有提供有关确切错误是什么的更多详细信息,我敢打赌它与“使用”将处理您的“上下文”这一事实有关,然后您稍后将尝试再次使用您的上下文。

数据上下文应该以原子方式使用。它们已经在内部编码为以这种方式高效,通常没有合理的理由让它们像您一样长时间运行。您看到大多数示例使用“using”的原因是因为它们在 using 之前(或其中)立即初始化了数据上下文,然后不尝试引用已处理的上下文。

最后一点,处置对象会导致它们释放所有内部内存引用(例如打开的连接、缓存的数据等)。

//Our context exists right now ... unless we've already called this method since the app started ;)
var myMembers = BLLCmo.GetAllMembers(workerID); // Context is disposed at the end of this call
if (myMembers.Rows.Count != 0)
{
  dgvMyMembers.DataSource = myMembers;  //No prob, we didn't call our function again
}
else
{
  var allMembers = BLLCmo.GetAllMembers();  // Oops, our context was disposed of earlier
  dgvMyMembers.DataSource = allMembers;
}

"using" blocks automatically dispose of the object you're using. Since you didn't give further details on what the exact error is, I'm betting its related to the fact that the "using" will dispose of your "context", and then later you'll try to use your context again.

Data Contexts should be used atomically. They're already internally coded to be efficient that way, there's usually no justifiable reason to have one as long-running as you do. The reason you see most samples that use a "using" is because they have the data context initialized immediately before the using (or in it) and then don't try to referenced the disposed context.

As a final note, disposing of objects causes them to release all their internal memory references (such as open connections, cached data, etc).

//Our context exists right now ... unless we've already called this method since the app started ;)
var myMembers = BLLCmo.GetAllMembers(workerID); // Context is disposed at the end of this call
if (myMembers.Rows.Count != 0)
{
  dgvMyMembers.DataSource = myMembers;  //No prob, we didn't call our function again
}
else
{
  var allMembers = BLLCmo.GetAllMembers();  // Oops, our context was disposed of earlier
  dgvMyMembers.DataSource = allMembers;
}
红墙和绿瓦 2024-08-12 07:51:17

如果您使用 using ,您会收到错误,因为上下文在 GetAllMembers() 第二次调用时被处置

如果您需要处理上下文,我建议您在 GetAllMembers() 中动态创建一个上下文,而不是使用静态上下文。

查看 IDisposable使用

以下是一篇文章的链接,可能会帮助您DataContext 的生命周期管理

You get an error if you use using because the context is disposed the second time it's called by GetAllMembers().

If you need to dispose the context I sugest you create one on the fly in the GetAllMembers() as opposed to having a static context.

Check out the documentation of IDisposable and using.

Here's a link to an article that might help you with Lifetime Management of DataContext.

萌辣 2024-08-12 07:51:17

我也遇到过这个问题,当时也不太明白。我刚刚删除了 using 并且它起作用了。问题是延迟加载。 DataContext 给了我一个实体,但后来我尝试访问父实体的属性(在外键的意义上)。因为这个父实体不是第一次加载,所以它尝试获取它,但 DataContext 消失了。所以我使用了DataLoadOptions。如果我知道我需要一个相关实体,我就会用原始实体加载它。

例如:您要求向数据上下文提供发票,但稍后您想要访问客户的名称,例如invoice.Client.Name。客户端尚未加载,因此名称不可用。

DataLoadOptions 对于性能也很重要,如果您在循环中需要此相关实体,并且不预加载子(或父)实体,则您将在循环时多次返回数据库。

I have had this problem and did not understand it either at that time. I just removed the using and it worked. The problem was Lazy Loading. The DataContext gave me an entity, but later I tried accessing a property of a parent entity (in the sense of a Foreign Key). Because this parent entity was not loaded the first time, it tried to get it but the DataContext was gone. So I used a DataLoadOptions. If I knew I needed a related entity, I loaded it with the original entity.

Ex: You ask for an invoice to your datacontext, but later you want to access the client's name, like in invoice.Client.Name. The client has not been loaded, so the name is not available.

DataLoadOptions are also important for performance, if you need this related entity in a loop, you'll go back to the DB as many times as you loop if you do not pre-load the child (or parent) entity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文