i am using SQL Mirroring.in connection i set “Failover Partner” in connection String of my C# app.in C# how can i detect current server that i load data from.
see the Image link That i upload.in SQL mirroring when you use EF6 can u detect current server?’Siavash Memarizadeh’ answer was correct but i want better solution in dbcontext properties.
5
Here’s a straightforward way to do it:
- Create and Open the Connection
Use aSqlConnection
with your failover partner in the connection string, then open it:using (var connection = new SqlConnection("Server=MyPrimaryServer;Failover Partner=MyMirrorServer;Database=MyDB;Integrated Security=true")) { connection.Open(); // 2. Check which server you're connected to string currentServer = connection.DataSource; Console.WriteLine("Current Server: " + currentServer); // 3. (Optional) Run a simple SQL query to confirm var cmd = new SqlCommand("SELECT CONVERT(sysname, SERVERPROPERTY('ServerName'))", connection); string serverName = (string)cmd.ExecuteScalar(); Console.WriteLine("Current Server (From SQL): " + serverName); }
connection.DataSource
gives you the actual data source (server) your app is currently connected to.- SQL Query Method (optional): You can use
SERVERPROPERTY('ServerName')
to confirm the exact instance name.
This way, you’ll always know whether you’re on the primary or the mirror server at runtime, which is especially useful after a failover.
4