简体   繁体   中英

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. How can i connect remote server by 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.

However, if you're only going to process some sql queries, I would suggest using SQL Server Management Studio instead. Entity Framework is an ORM, not a database management tool.

1) Check if remote sql server is allowed remote connetions

2) In Visual Studio use Entity Framework wizard (add new connection)

Here how I connect programmatically (no xml/appconfig file) to a remote server:

  1. First check that your remote server is correctly parametrised. In particular one port has to be open. See this MSDN post for details.
  2. Create the connection string as follow (see 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(); } 
  3. Then connect via the DbContext :

     public class MDBContext : DbContext { public MDBContext () : base(GetRemoteConnectionString()) { } ...... } 

Extra :

  • You can also easily check connection (before to create the DbContext) as follow :

      try { using (SqlConnection con = new SqlConnection(GetRemoteConnectionString())) { con.Open(); } success = true; } catch (Exception ex) { success = false; ... } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM