代码之家  ›  专栏  ›  技术社区  ›  Mark Wilkins

是否可以在VS2010的DDL生成模板中检索连接字符串?

  •  2
  • Mark Wilkins  · 技术社区  · 16 年前

    我正在为visual studio 2010 rc中的“ddl生成模板选项”(model first)流程创建一个t4模板。是否可以检索与该进程关联的连接字符串?如果右键单击.edmx文件并选择“从模型生成数据库…”,则可以选择数据连接。该连接字符串将保存到app.config(假设选中了该选项)。所以我想知道是否可以在t4模板中检索该连接字符串。我想根据连接字符串从模板生成不同的信息。

    更一般地说,在这种情况下,是否可以获得任何上下文信息?到目前为止,我唯一成功检索到的是.NET数据提供程序名称。

    注意-我已经研究了Craig提供的想法,但只得到了IDE(devenv.exe)的名称,这很可能意味着我只是做错了什么。

    3 回复  |  直到 16 年前
        1
  •  1
  •   Craig Stuntz    16 年前

    嗯,ef连接字符串将始终与模型同名,对吧?DB连接字符串将嵌入EF连接字符串中。所以我认为你应该能够通过ef连接字符串,至少是间接地得到它。

    因为您没有在程序集中运行,所以必须指定配置文件名。

    所以可能是这样的:

    var config = ConfigurationManager.OpenExeConfiguration(name);
    var cs = config.ConnectoinStrings[modelName];
    

    注意 name ,这里应该是一个exe名称。但是在IDE中,你的配置函数将被调用 App.config 而不是 MyApp.dll.config . 所以你可能要玩这个才能让它工作——试着用“app”作为exe名!

    最坏的情况是将其作为文件打开,然后使用配置管理器。

        2
  •  4
  •   The Car    14 年前

    如果这对其他人有帮助,这里是我创建的一个片段,用于从t4内部读取实体框架连接字符串。将模型名(也是连接字符串的名称)传递给它。它只找到并解析我需要的连接位。如果失败,它也会抛出有用的错误。

    使用:

    a.如果尚未引用这些程序集,请将其粘贴到模板顶部:

    <#@ assembly name="EnvDTE" #>
    <#@ assembly name="System.Configuration" #>
    

    b.将这个难看(但紧凑)的代码粘贴到模板的末尾:

    <#+
    string GetEFConnectionString(string modelName)
    {
        string file = null, key = "provider connection string=\"";
        foreach (EnvDTE.ProjectItem item in ((EnvDTE.Project)((Array)((EnvDTE.DTE)((IServiceProvider)this.Host).GetService(typeof(EnvDTE.DTE))).ActiveSolutionProjects).GetValue(0)).ProjectItems)
            if (System.Text.RegularExpressions.Regex.IsMatch(item.Name, "(app|web).config", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) {
                file = item.get_FileNames(0); break;
            }
        if (file == null) throw new Exception("config file could not be found");
        var config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = file }, System.Configuration.ConfigurationUserLevel.None);
        var cn = config.ConnectionStrings.ConnectionStrings[modelName];
        if (cn == null) throw new Exception(modelName + " connection string could not be found");
        string s = cn.ConnectionString;    
        int pos = s.IndexOf(key,StringComparison.OrdinalIgnoreCase);    
        if (pos<0) throw new Exception("could not find value '" + key + "' inside connection string");
        pos += key.Length;
        int pos2=s.IndexOf('"',pos);
        if (pos2 < 0) throw new Exception("could not find ending \" in connection string");
        return s.Substring(pos,pos2-pos);
    }
    #>
    

    c.像这样使用:

    using(var connection = new SqlConnection(GetEFConnectionString("Database"))) {
        ..
    }    
    
        3
  •  3
  •   Mark Wilkins    16 年前

    我在msdn的一个论坛上发布了我的问题,得到了孙凌志的回复,他给我指出了skysanders.net上几个链接的方向。这些链接中的第二个有一个非常好的例子,可以访问app/web.config文件,特别是我想要的部分,连接字符串。它没有提供任何关于我在最初问题中描述的场景的特定连接字符串的信息,但是这让我足够接近了。

    推荐文章