Entity Framework 6 set connection string in code

后端 未结 5 960
长发绾君心
长发绾君心 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 14:53

    You can use singleton patter for it . For example

    private YouurDBContext context;
    
        public YouurDBContext Context
        {
            get
            {
                if (context==null)
                {
                    context = new YouurDBContext();
                }
                return context;
    
            }
            set { context = value; }
        }
    
    0 讨论(0)
  • 2020-12-25 15:00

    I got this solution using below code, I can hardcode connection string using C# code without using config file.

     public class SingleConnection
        {
            private SingleConnection() { }
            private static SingleConnection _ConsString = null;
            private String _String = null;
    
            public static string ConString
            {
                get
                {
                    if (_ConsString == null)
                    {
                        _ConsString = new SingleConnection { _String = SingleConnection.Connect() };
                        return _ConsString._String;
                    }
                    else
                        return _ConsString._String;
                }
            }
    
            public static string Connect()
            {
                //Build an SQL connection string
                SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
                {
                    DataSource = "SIPL35\\SQL2016".ToString(), // Server name
                    InitialCatalog = "Join8ShopDB",  //Database
                    UserID = "Sa",         //Username
                    Password = "Sa123!@#",  //Password
                };
                //Build an Entity Framework connection string
                EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
                {
                    Provider = "System.Data.SqlClient",
                    Metadata = "res://*/ShopModel.csdl|res://*/ShopModel.ssdl|res://*/ShopModel.msl",
                    ProviderConnectionString = @"data source=SIPL35\SQL2016;initial catalog=Join8ShopDB2;user id=Sa;password=Sa123!@#;"// sqlString.ToString()
                };
                return entityString.ConnectionString;
            }
    

    and using DbContext using like this:

    Join8ShopDBEntities dbContext = new Join8ShopDBEntities(SingleConnection.ConString);
    
    0 讨论(0)
  • 2020-12-25 15:07

    How about:

    public partial class MyDatabaseEntities : DbContext
    {
    public MyDatabaseEntities(string connectionString)
        : base(connectionString)
    {
    }
    
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }
    
    public virtual DbSet<MyTable> MyTable { get; set; }
    

    }

    Then initialize your database like you did before:

    string myConnectionString = "...";
    MyDatabaseEntities = new MyDatabaseEntities(myConnectionString);
    
    0 讨论(0)
  • 2020-12-25 15:09

    Thanks a lot . I changed little for Code First EF6.

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.Entity.Core.EntityClient;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Data
    {
        public class SingleConnection
        {
            private SingleConnection() { }
            private static SingleConnection _ConsString = null;
            private String _String = null;
    
            public static string ConString
            {
                get
                {
                    if (_ConsString == null)
                    {
                        _ConsString = new SingleConnection { _String = SingleConnection.Connect() };
                        return _ConsString._String;
                    }
                    else
                        return _ConsString._String;
                }
            }
    
            public static string Connect()
            {
                string conString = ConfigurationManager.ConnectionStrings["YourConnectionStringsName"].ConnectionString;
    
                if (conString.ToLower().StartsWith("metadata="))
                {
                    System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder efBuilder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(conString);
                    conString = efBuilder.ProviderConnectionString;
                }
    
                SqlConnectionStringBuilder cns = new SqlConnectionStringBuilder(conString);
                string dataSource = cns.DataSource;
    
    
                SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
                {
                    DataSource = cns.DataSource, // Server name
                    InitialCatalog = cns.InitialCatalog,  //Database
                    UserID = cns.UserID,         //Username
                    Password = cns.Password,  //Password,
                    MultipleActiveResultSets = true,
                    ApplicationName = "EntityFramework",
    
                };
                //Build an Entity Framework connection string
                EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
                {
                    Provider = "System.Data.SqlClient",
                    Metadata = "res://*",
                    ProviderConnectionString = sqlString.ToString()
                };
                return entityString.ConnectionString;
            }
        }
    }
    
    0 讨论(0)
  • 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));
    
    0 讨论(0)
提交回复
热议问题