Hi,@Dimitri Garmaise .Welcome Microsoft Q&A. Not sure about your coding environment and the method you are using. You could try to refer to the following code. If you have any questions please let me know.
App Configuration:
You can store your connection strings in your WPF application's configuration file (App.config or AppSettings.json). Create separate configurations for development and production environments. Here's an example of how you might structure your App.config file:
<connectionStrings>
<add name="DevDbContext" connectionString=..." providerName="System.Data.SqlClient" />
<add name="ProdDbContext" connectionString="..." providerName="System.Data.SqlClient" />
</connectionStrings>
Create a Factory:
Implement a factory or service to retrieve the appropriate connection string based on your application's environment. You can use conditional compilation symbols or app settings to determine the environment. Here's an example of a simple factory:
public class DbContextFactory
{
public static YourDbContext CreateDbContext()
{
string connectionString;
#if DEBUG
connectionString = ConfigurationManager.ConnectionStrings["DevDbContext"].ConnectionString;
#else
connectionString = ConfigurationManager.ConnectionStrings["ProdDbContext"].ConnectionString;
#endif
var optionsBuilder = new DbContextOptionsBuilder<YourDbContext>();
optionsBuilder.UseSqlServer(connectionString);
return new YourDbContext(optionsBuilder.Options);
}
}
Usage:
Whenever you need to create an instance of your DbContext
, use the factory method:
using (var dbContext = DbContextFactory.CreateDbContext())
{
// Use dbContext for database operations
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.