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:
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(); }
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.