How to use a dynamic connection string using a Model First approach but still use the data model in the EDMX?

后端 未结 1 872
野趣味
野趣味 2020-12-28 22:19

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 define

1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-28 23:01

    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;
      }
    }
    

    Basic usage is something like:

    string connString = 
      ConfigurationMananager.ConnectionStrings["name"].ConnectionString;
    
    string dbConnectionString = ContextConnectionStringBuilder(connString,
                                                               typeof(MyDbContext));
    
    var dbContext = new MyDbContext(dbConnectionString);
    

    0 讨论(0)
提交回复
热议问题