如何使用 Model First 方法使用动态连接字符串,但仍使用 EDMX 中的数据模型? [英] How to use a dynamic connection string using a Model First approach but still use the data model in the EDMX?

查看:20
本文介绍了如何使用 Model First 方法使用动态连接字符串,但仍使用 EDMX 中的数据模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 EF 5 和 Model First 方法创建了一个 EDMX,即我从一个空白的设计器开始并为我的实体建模.现在我希望能够使用在 EDMX 中定义的这个模型,但在不修改配置文件的情况下提供运行时 SQL Server 连接字符串.

I have created an EDMX using EF 5 with the Model First approach, i.e. I started with a blank designer and modeled my entities. Now I want to be able to use this model defined in the EDMX but supply runtime SQL Server connection strings without modyfing the config file.

我知道如何将连接字符串传递给 DbContext,但问题是在程序集中定位映射的元数据.

I know how to pass a connection string to the DbContext but the issue is locating the metadata for the mappings within the assembly.

例如,我的 EDMX 在 app.config 中有这个连接字符串

For example, my EDMX has this connection string in the app.config

<add name="MesSystemEntities" connectionString="metadata=res://*/Data.DataContext.EntityFramework.MesSystem.csdl|res://*/Data.DataContext.EntityFramework.MesSystem.ssdl|res://*/Data.DataContext.EntityFramework.MesSystem.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MyMachine;initial catalog=MesSystem;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

我缺少的部分是 "metadata=res://*/Data.DataContext.EntityFramework.MesSystem.csdl|res://*/Data.DataContext.EntityFramework.MesSystem.ssdl|res://*/Data.DataContext.EntityFramework.MesSystem.msl;"

我希望能够创建一个 DbContext 以编程方式传入 SQL Server 连接字符串,但添加"元数据部分.

I want to be able to create a DbContext programmatically passing in a SQL Server connection string but "add on" the metadata portion.

这是我想由T4文件生成的...

This is what I would like to be generated by the T4 file...

public partial class MesSystemEntities : DbContext
{
    public MesSystemEntities()
        : base("name=MesSystemEntities")
    {
    }

    public MesSystemEntities(string sqlServerConnectionString)
        : base(GetEfConnectionString(sqlServerConnectionString))
    {    
    }

    private string GetEfConnectionString(string sqlServerConnectionString)
    {
       // values added by T4 generation
       string format = "metadata=res://*/Data.DataContext.EntityFramework.MesSystem.csdl|res://*/Data.DataContext.EntityFramework.MesSystem.ssdl|res://*/Data.DataContext.EntityFramework.MesSystem.msl;;provider=System.Data.SqlClient;provider connection string="{0}"";    
       return String.Format(format, sqlServerConnectionString);
    }
...
}

我的问题是如何在 T4 生成文件中获取我需要的元数据来创建实体框架连接,而无需为每个 EDMX 文件对其进行硬编码

My question is how can I get the metadata I need in the T4 generation file to create the Entity Framework connection without hardcoding it for each EDMX file

OR

是否有更简单的方法以编程方式从程序集中加载元数据?

is there an easier way to load the metadata from the assembly programmatically?

推荐答案

我遇到了同样的问题,所以我没有依赖连接字符串中的所有元数据(我认为这不是一个好主意)我写了一个方法从标准连接字符串创建它.(我可能应该将其重构为 DbContext 的扩展方法,但这应该可以)

I had the same issue, so instead of relying on all the meta data in the connection string (which I think is not a good idea) I wrote a method to create it from a standard connection string. (I should probably refactor it into an Extension method for DbContext, but this should do)

internal static class ContextConnectionStringBuilder
{
  // Modified Version of http://stackoverflow.com/a/2294308/209259
  public static string GetEntityConnectionString(string ConnectionString, 
                                                 Type ContextType)
  {
    string result = string.Empty;

    string prefix = ContextType.Namespace
      .Replace(ContextType.Assembly.GetName().Name, "");

    if (prefix.Length > 0
        && prefix.StartsWith("."))
    {
      prefix = prefix.Substring(1, prefix.Length - 1);
    }

    if (prefix.Length > 1
        && !prefix.EndsWith("."))
    {
      prefix += ".";
    }


    EntityConnectionStringBuilder csBuilder = 
      new EntityConnectionStringBuilder();

    csBuilder.Provider = "System.Data.SqlClient";
    csBuilder.ProviderConnectionString = ConnectionString.ToString();
    csBuilder.Metadata = string.Format("res://{0}/{1}.csdl|"
                                        + "res://{0}/{1}.ssdl|"
                                        + "res://{0}/{1}.msl"
                                        , ContextType.Assembly.FullName
                                        , prefix + ContextType.Name);

    result =  csBuilder.ToString();

    return result;
  }
}

基本用法类似于:

string connString = 
  ConfigurationMananager.ConnectionStrings["name"].ConnectionString;

string dbConnectionString = ContextConnectionStringBuilder(connString,
                                                           typeof(MyDbContext));

var dbContext = new MyDbContext(dbConnectionString);

这篇关于如何使用 Model First 方法使用动态连接字符串,但仍使用 EDMX 中的数据模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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