How do I create connection string programmatically to MS SQL in Entity Framework 6?

后端 未结 5 1704
一整个雨季
一整个雨季 2021-02-14 02:55

How do I create connection string programmatically to MS SQL in Entity Framework 6?

I\'m using c# and WPF and I was wondering if someone could show me how or link me to

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-14 03:15

    If you are specifically connecting to a MS Sql database, this should work:

    private DbConnection CreateConnection(string connectionString)
    {
        return new SqlConnection(connectionString);
    }
    
    private string CreateConnectionString(string server, string databaseName, string userName, string password)
    {
        var builder = new SqlConnectionStringBuilder
        {
            DataSource = server, // server address
            InitialCatalog = databaseName, // database name
            IntegratedSecurity = false, // server auth(false)/win auth(true)
            MultipleActiveResultSets = false, // activate/deactivate MARS
            PersistSecurityInfo = true, // hide login credentials
            UserID = userName, // user name
            Password = password // password
        };
        return builder.ConnectionString;
    }
    

    how to use:

    public void ConnectoToDbWithEf6()
    {
        using(var connection = CreateConnection(CreateConnectionString("server", "db", "you", "password")
        {
            using(var context = new YourContext(connection, true))
            {
                foreach(var someEntity in context.SomeEntitySet)
                {
                    Console.WriteLine(someEntity.ToString());
                }
            }
        }
    
    }
    

    see https://msdn.microsoft.com/en-Us/library/system.data.sqlclient.sqlconnectionstringbuilder%28v=vs.100%29.aspx

提交回复
热议问题