Entity Framework 6 set connection string in code

后端 未结 5 959
长发绾君心
长发绾君心 2020-12-25 14:37

I have a dll that uses the Entity Framework 6 to do some database operations. I\'m using a database first approach. The model and everything concerning the Entity Framework,

5条回答
  •  醉梦人生
    2020-12-25 15:16

    I had the similar issue. My Edmx and App.Config was in a different project. My startup project was different, had 3 different connection strings, we need to choose one on the fly depending on the environment. So couldn't use a fixed connection string. I created a partial class overload of the Context.cs using the same namespace. Following was my default Context.cs;

    namespace CW.Repository.DBModel
    {
    
      public partial class CWEntities : DbContext
      {
          public CWEntities()
            : base("name=CWEntities")
          {
          }
    
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
            throw new UnintentionalCodeFirstException();
          }
      ...
      ...
      }
    }
    

    My partial class overload;

    namespace CW.Repository.DBModel
    {
        public partial class CWEntities : DbContext
        {
            public CWEntities(string ConnectionString)
                : base(ConnectionString)
            {
            }        
        }
    }
    

    Lastly, as my connection strings were not for EF, I converted them to a EF connection string.

    public static string GetEntityConnectionString(string connectionString)
        {
            var entityBuilder = new EntityConnectionStringBuilder();
    
            // WARNING
            // Check app config and set the appropriate DBModel
            entityBuilder.Provider = "System.Data.SqlClient";
            entityBuilder.ProviderConnectionString = connectionString + ";MultipleActiveResultSets=True;App=EntityFramework;";
            entityBuilder.Metadata = @"res://*/DBModel.CWDB.csdl|res://*/DBModel.CWDB.ssdl|res://*/DBModel.CWDB.msl";
    
            return entityBuilder.ToString();
        }
    

    Lastly, the calling

    var Entity = new CWEntities(CWUtilities.GetEntityConnectionString(ConnectionString));
    

提交回复
热议问题