wpf 如何在实体框架 6 中以编程方式创建到 MS SQL 的连接字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21729967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:49:18  来源:igfitidea点击:

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

c#sql-serverwpfentity-framework-6

提问by Bob

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

如何在实体框架 6 中以编程方式创建到 MS SQL 的连接字符串?

I'm using c# and WPF and I was wondering if someone could show me how or link me to a resource that shows how to set up connection strings programmatically in EF 6. The MSDN article explains that you can http://msdn.microsoft.com/en-us/data/jj680699#movingbut it doesn't go into creating actual connection strings.

我正在使用 c# 和 WPF,我想知道是否有人可以向我展示如何或将我链接到展示如何在 EF 6 中以编程方式设置连接字符串的资源。MSDN 文章解释说,您可以http://msdn.microsoft .com/en-us/data/jj680699#moving但它不会创建实际的连接字符串。

So here is an EF6 example that works

所以这是一个有效的 EF6 示例

App.Config

应用程序配置

entityFramework codeConfigurationType="WPFwithEF.SqlConfiguration, WPFwithEF"> /entityFramework

entityFramework codeConfigurationType="WPFwithEF.SqlConfiguration, WPFwithEF"> /entityFramework

context

语境

public class ProductContext : DbContext
{  
    public ProductContext():base("Wpf")
    { }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

Configuration.cs

配置文件

namespace WPFwithEF
{
public class SqlConfiguration : DbConfiguration
{

    public SqlConfiguration()
    {
        SetProviderServices(SqlProviderServices.ProviderInvariantName,SqlProviderServices.Instance);           
        SetDefaultConnectionFactory(new SqlConnectionFactory());
    }
}
}

but if the context base is "name=Wpf" then this set up does not work is there a way to make that work? And i'm looking for the latest EF6 not the old way to do it.

但是如果上下文基础是“name = Wpf”,那么这个设置不起作用有没有办法让它起作用?我正在寻找最新的 EF6,而不是旧的方法。

回答by csteinmueller

You can use the EntityConnectionStringBuilderas descriped here: How to: Build an EntityConnection Connection String

您可以使用EntityConnectionStringBuilder此处描述的方法:如何:构建 EntityConnection 连接字符串

回答by hoekki

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

如果您专门连接到 MS Sql 数据库,这应该有效:

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

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

回答by NicoJuicy

I previously used the DefaultConnection string found in the app.config ( or web.config) as example and just replaced the "connectionstring" on the DbContext, to the one i wanted.

我以前使用在 app.config(或 web.config)中找到的 DefaultConnection 字符串作为示例,只是将 DbContext 上的“连接字符串”替换为我想要的字符串。

The connectionstring looked something like :

连接字符串看起来像:

Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ShoppingList.Web-20150903103641.mdf;Initial Catalog=aspnet-ShoppingList.Web-20150903103641;Integrated Security=True

If i'm remembering correctly, you should replace the connectionstring in :

如果我没记错的话,您应该将连接字符串替换为:

DbContext.Database.Connection.Connectionstring

PS. You can only use it this way if you are using Code-First. If you are using Model-First or Database-First you should use the EntityConnectionStringBuilder .

附注。如果您使用 Code-First,则只能以这种方式使用它。如果您使用 Model-First 或 Database-First,您应该使用 EntityConnectionStringBuilder 。

回答by Pawel Wujczyk

You could use the ProductivityTools.ConnectionStringnuget package. It has 3 methods:

您可以使用ProductivityTools.ConnectionStringnuget 包。它有3种方法:

  • Creates connection string to server without database name
  • Creates connection string to server with the database name
  • Creates connection string for EntityFramework database context
  • 创建到没有数据库名称的服务器的连接字符串
  • 使用数据库名称创建到服务器的连接字符串
  • 为 EntityFramework 数据库上下文创建连接字符串

Last method will be right for you and asssuming that your edmx is named Product after invocation

最后一种方法适合您,并假设您的 edmx 在调用后命名为 Product

ConnectionStringHelper.ConnectionString.GetSqlEntityFrameworkConnectionString
("serverName", "databaseName", "Product");

Package will return:

包裹将返回:

metadata=res://*/Product.csdl|res://*/Product.ssdl| res://*/Product.msl; 
provider=System.Data.SqlClient;provider connection string="Data Source=serverName;
Initial Catalog=databaseName;Integrated Security=True"

回答by JRB

I investigated this question today. in my opinion the easiest solution is not mentioned above.

我今天调查了这个问题。在我看来,上面没有提到最简单的解决方案。

Why not use the SqlConnectionStringBuilder class? (using System.Data.SqlClient)

为什么不使用 SqlConnectionStringBuilder 类?(使用 System.Data.SqlClient)

Here a simple example how to use it.

这是一个如何使用它的简单示例。

    SqlConnectionStringBuilder sqlb = new  SqlConnectionStringBuilder(getConnectionString(DATABASENAME);

    using (SqlConnection connection = new SqlConnection(sqlb.ConnectionString))
    ...
    )

    // works for EF Core, should also work for EF6 (haven't tried this) 
    private static string getConnectionString(string databaseName)
    {
        return "Data Source=SQLSERVERNAME;Initial Catalog="+databaseName+";Integrated Security=True";
    }