Code First Entity Framework WPF MVVM C#中的动态连接字符串 [英] Dynamic connection string in Code First Entity Framework WPF MVVM C#

查看:76
本文介绍了Code First Entity Framework WPF MVVM C#中的动态连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的wpf应用程序中,用户可以选择在SqlServer,MySql和Oracle中加载数据。我从SqlSErver开始,我的上下文如下所示。

 public class SqlServerDbContext:DbContext 
{
public SqlServerDbContext():base()
{

}
public SqlServerDbContext(string SqlServerDBConn):base(SqlServerDBConn)
{

}

}

我使用以下代码调用上下文:

 using(var ctx = new DbServerDbContext( ))
{
//强制初始化
ctx.Database.Initialize(true);
}

虽然上面的代码可以使用< namespace>来创建数据库。< classname> ,当我想加载用户输入的sql server详细信息的上下文(用户将提供sql server,db name,user和password,winauth = false)时,它无法初始化
db以下错误:


EntityFramework.SqlServer.dll中出现"System.Data.SqlClient.SqlException"类型的异常,但未在用户代码中处理



其他信息:建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确,并且SQL Server配置为允许
远程连接。 (提供者:命名管道提供程序,错误:40 - 无法打开与SQL Server的连接)




{"系统无法找到指定的文件"}


以下是构建我的连接字符串的方式:


 

public static string ConnectToSqlServer(string hostServer ="。",string catalogDbName =" TestDB",string user ="",string pass = ",",bool winAuth = true)
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
{
DataSource = hostServer,
InitialCatalog = catalogDbName,
PersistSecurityInfo = true,
IntegratedSecurity = winAuth,
MultipleActiveResultSets = true,

UserID = user,
Password = pass,
};

//假设MyDbEntities的.config中的connectionString名称
var entityConnectionStringBuilder = new EntityConnectionStringBuilder
{
Provider =" System.Data.SqlClient",
ProviderConnectionString = sqlBuilder.ConnectionString,
元数据=" res:// * /",

//或
//元数据=" res:// * /DbModel.csdl |res://*/DbModel.ssdl|res://*/DbModel.msl",
};

//// //使用
//使用(EntityConnection conn =
//新EntityConnection(entityConnectionStringBuilder.ToString()))
// {
// conn.Open();
// Console.WriteLine("仅测试连接。");
// conn.Close();
//}

//返回entityConnectionStringBuilder.ConnectionString;
返回sqlBuilder.ConnectionString;
}

我正在尝试使用sqlBuilderr.ConnectionString,它给出了我指定的错误。如果我在上面的代码中返回
entityConnectionStringBuilder,我不知道我需要为csdl提供什么值,msdl ,msl,如果我使用/ * /它不起作用。


我还应该更改代码中的任何内容,除了
" System.Data.SqlClient的"使其适用于MySql或Oracle。


 





Krrishna

解决方案

您最好发布到EF论坛寻求帮助。


http://social.msdn.microsoft.com /论坛/ EN-US /家?论坛= adodotnetentityframework


In our wpf application users have a choice to choose among SqlServer, MySql, and Oracle to load the data. I started with SqlSErver and my context is like below.

 public class SqlServerDbContext : DbContext
    {
        public SqlServerDbContext():base()
        {

        }
        public SqlServerDbContext(string SqlServerDBConn) : base(SqlServerDBConn)
        {

      }

}

And  i call the context using below code :

 using (var ctx = new DbServerDbContext())
            {
                //force the initialization
                ctx.Database.Initialize(true);
            }

While the above code works and creates a database with <namespace>.<classname> , when i want to load the context for user entered sql server details (user will provide sql server,db name,user and password,winauth=false) , it fails to initialize the db with below errror:

An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

{"The system cannot find the file specified"}

Below is the way i am constructing my connectionstring:

public static string ConnectToSqlServer(string hostServer = ".", string catalogDbName = "TestDB", string user = "", string pass = "", bool winAuth = true) { SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder { DataSource = hostServer, InitialCatalog = catalogDbName, PersistSecurityInfo = true, IntegratedSecurity = winAuth, MultipleActiveResultSets = true, UserID = user, Password = pass, }; // assumes a connectionString name in .config of MyDbEntities var entityConnectionStringBuilder = new EntityConnectionStringBuilder { Provider = "System.Data.SqlClient", ProviderConnectionString = sqlBuilder.ConnectionString, Metadata = "res://*/",

// or //Metadata = "res://*/DbModel.csdl|res://*/DbModel.ssdl|res://*/DbModel.msl", }; //// //works though //using (EntityConnection conn = // new EntityConnection(entityConnectionStringBuilder.ToString())) //{ // conn.Open(); // Console.WriteLine("Just testing the connection."); // conn.Close(); //} // return entityConnectionStringBuilder.ConnectionString; return sqlBuilder.ConnectionString; }

I am trying to use sqlBuilderr.ConnectionString which gives the error i specified. If i return entityConnectionStringBuilder in above code i am not sure what values i need to provider for csdl,msdl,msl, if i use /*/ it doesn't work.

And also should i change anything in my code except "System.Data.SqlClient" to make it work with MySql or Oracle.

 


Krrishna

解决方案

You best post to the EF forum for help.

http://social.msdn.microsoft.com/Forums/en-US/home?forum=adodotnetentityframework


这篇关于Code First Entity Framework WPF MVVM C#中的动态连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆