[英]How can i connect remote sql server by Entity Framework?
I have no enough experience on database systems. 我对数据库系统没有足够的经验。 I have to connect to remote sql server and process some queries on it.
我必须连接到远程SQL Server并对其进行一些查询。 How can i connect remote server by Entity Framework ?
如何通过Entity Framework连接远程服务器?
Same as you would with any other database connection tool: Make sure the server and all firewalls/proxy servers between you and the server accepts the connection, and then supply EF with a correct connection string. 与使用任何其他数据库连接工具相同:确保服务器以及您与服务器之间的所有防火墙/代理服务器都接受连接,然后为EF提供正确的连接字符串。
However, if you're only going to process some sql queries, I would suggest using SQL Server Management Studio instead. 但是,如果您仅要处理一些sql查询,建议您改用SQL Server Management Studio。 Entity Framework is an ORM, not a database management tool.
实体框架是一个ORM,而不是数据库管理工具。
1) Check if remote sql server is allowed remote connetions 1)检查是否允许远程SQL Server远程连接
2) In Visual Studio use Entity Framework wizard (add new connection) 2)在Visual Studio中使用实体框架向导(添加新连接)
Here how I connect programmatically (no xml/appconfig file) to a remote server: 在这里,我如何以编程方式(没有xml / appconfig文件)连接到远程服务器:
Create the connection string as follow (see SqlConnectionStringBuilder ): 创建连接字符串,如下所示(请参阅SqlConnectionStringBuilder ):
public static string GetRemoteConnectionString() { SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder() { DataSource = $"{IP},{PORT}", // ex : 37.59.110.55,1433 InitialCatalog = "MyDatabaseName", //Database IntegratedSecurity = false, MultipleActiveResultSets = true, ApplicationName = "EntityFramework", UserID = "MyUserId", Password = "MyPassword" }; return sqlString.ToString(); }
Then connect via the DbContext : 然后通过DbContext连接:
public class MDBContext : DbContext { public MDBContext () : base(GetRemoteConnectionString()) { } ...... }
Extra : 额外:
You can also easily check connection (before to create the DbContext) as follow : 您还可以轻松地检查连接(在创建DbContext之前),如下所示:
try { using (SqlConnection con = new SqlConnection(GetRemoteConnectionString())) { con.Open(); } success = true; } catch (Exception ex) { success = false; ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.