Linq to SQL DataContext生命周期管理问题 [英] Linq to SQL DataContext Lifetime Management Issue

查看:82
本文介绍了Linq to SQL DataContext生命周期管理问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了里克·斯特拉尔(Rick Strahl)的文章,内容涉及如何处理数据上下文.我的DBML位于类库中,我通过在库中单独的自定义局部类中创建静态Current方法来保持数据上下文打开.

I read Rick Strahl's article about ways to deal with the data context. My DBML is inside a class library, I keep my data context open by creating a static Current method in a separate custom partial class within library.

public partial class DataContext
{
    public static DataContext Current
    {
        get
        {
            DataContext dc = HttpContext.Current.Items["dc"] as DataContext;
            if (dc == null)
            {
                dc = new ImmediacyPageDataContext();
                HttpContext.Current.Items["dc"] = dc;
            }

            return dc;
        }
    }

然后像这样访问它

DataContext dc = DataContext.Current;

但是,每当我更新DBML文件时,这都会导致问题.在每次尝试构建项目后编辑DBML文件后,设计器文件都不会重新生成/不会被删除.如果我尝试运行自定义工具选项,则会返回错误.

However, this causes issues whenever I update my DBML file. After editing the DBML file whenever I try and build the project my designer file doesn't regenerate/gets deleted. If I try running the custom tool option it comes back with an error.

解决此问题的唯一方法是重命名或删除自定义部分类,重新生成设计器文件,然后将自定义部分类添加回解决方案中.这确实是可行的,但是..有点痛苦.

The only way I can get round this is by renaming or deleting the custom partial class, re-generating the designer file, then adding my custom partial class back into the solution. This is a does work, but.. its a bit of a pain.

是否有更好的方法可以使编辑我的DBML文件变得更容易,同时又尽可能延长DC的时间?

Is there a better approach to take that will make editing my DBML files easier, while prolonging my DC for as long as possible ?

推荐答案

与部分DataContext类一起进入代码文件,并将using语句移至名称空间.出于某种原因,除非是这种情况,否则该工具将无法生成设计器.

Go into the code file with your partial DataContext class and move your using statements into your namespace. For some reason the tool will not generate the designer unless this is the case.

namespace MyNamespace
{
    using System;
    using System.Data.Linq;
    using System.Data.Linq.Mapping;
    using System.Reflection;
    using System.Xml.Linq;

    partial class DataContext
    {
    }
}

我相信从VS2008迁移到VS2008 SP1时需要进行此更改,尽管我可能会混淆一些版本.

I believe this change was required when moving from VS2008 to VS2008 SP1, though I may be mixing up some versions.

这篇关于Linq to SQL DataContext生命周期管理问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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