Entity Framework 6 set connection string in code

后端 未结 5 981
长发绾君心
长发绾君心 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: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);
    

提交回复
热议问题