How to change db connection programmatically c# Entity Framework - c#

I've built my project and named the db connection "VMaxEntities"
The connection string exists in web.config.
I have another connection string "Development_VMaxEntities"
Whenever I call the db, I use the code using (VMaxEntities db = new VMaxEntities())
This calls:
public partial class VMaxEntities : DbContext
{
public VMaxEntities()
: base("name=VMaxEntities")
{
}
What I want to do is connect to a development database instead of the live one, IF the current URI contains localhost.
So - thanks to cgotberg's answer below, here's what I used to get it working: (note, I add the password here instead of in web.config)
public VMaxEntities()
: base("name=Secure_VMaxEntities")
{
if (System.Web.HttpContext.Current.Request.Url.Host == "localhost")
{
var connectionString = this.Database.Connection.ConnectionString + ";password=***********";
this.Database.Connection.ConnectionString = connectionString.Replace("catalog=VMax", "catalog=DEV_VMax");
}
else
{
this.Database.Connection.ConnectionString += ";password=************";
}
}

I've done something like this in the past
using(var db = new VMaxEntities())
{
var connectionString = context.Database.Connection.ConnectionString;
var datasource = context.Database.Connection.DataSource;
var databaseServer = "yourDevDatabaseServerName"
db.Database.Connection.ConnectionString = connectionString.Replace(datasource, databaseServer);
}

Related

Entity Framework MySql: Argument 'xmlReader' not valid

I am trying to use Entity Framework for with MySql with dynamic connection string, i.e. connection string is determined at runtime.
I included Entity Framework and EF MySql via NuGet.
I build my Model Code First from existing database.
I extended the Model to work with a connection string and added a static method to generate the connection string:
public partial class Model1
{
public Model1(string nameOrConnectionString) : base(nameOrConnectionString) { }
public static string GetConnectionString()
{
var sqlCsBuilder = new MySqlConnectionStringBuilder();
sqlCsBuilder.Server = "myhost";
sqlCsBuilder.UserID = "myuser";
sqlCsBuilder.Password = "mypass";
sqlCsBuilder.Database = "mydb";
var connectionString = sqlCsBuilder.ToString();
var entityConnectionStringBuilder= new EntityConnectionStringBuilder();
entityConnectionStringBuilder.Provider = "MySql.Data.MySqlClient";
entityConnectionStringBuilder.ProviderConnectionString = connectionString;
entityConnectionStringBuilder.Metadata = "res://*";
var entityConnectionString = entityConnectionStringBuilder.ToString();
return entityConnectionString;
}
}
Initiating connection seems to work, or at least does not throw any errors, but it throws when trying the first read operation:
using (var db = new Model1(Model1.GetConnectionString()))
{
var items = db.mytable.Where(i => i.ID < 1000);
}
Instantiating the Model1 object works, but the .Where causes an exception:
Additional information: Argument 'xmlReader' is not valid.
A minimum of one .ssdl artifact must be supplied.
Does anyone know what's wrong?

How to add a sql database to an elastic pool programmatically?

I have the following console application which creates a ShardManagerDB and creates one database for each company on the main database.
I can see on azure the databases created on the server however they are not on the elastic pool.
Question:
1. Is this doable with the current API?
2. If not, what are other recommended approaches?
using System.Data.SqlClient;
using mynm.Data;
using System.Linq;
using mynm.Models.GlobalAdmin;
namespace mynm.DbManagementTool
{
class Program
{
static void Main(string[] args)
{
SetupSSM();
}
//This will create the Shard Management DB if it doesnt exist
private static void SetupSSM()
{
SqlConnectionStringBuilder connStrBldr = new SqlConnectionStringBuilder
{
UserID = SettingsHelper.AzureUsernamedb,
Password = SettingsHelper.AzurePasswordDb,
ApplicationName = SettingsHelper.AzureApplicationName,
DataSource = SettingsHelper.AzureSqlServer
};
DbUtils.CreateDatabaseIfNotExists(connStrBldr.ConnectionString, SettingsHelper.Azureshardmapmgrdb);
Sharding sharding = new Sharding(SettingsHelper.AzureSqlServer, SettingsHelper.Azureshardmapmgrdb, connStrBldr.ConnectionString);
CreateShardPerCompany(sharding);
}
private static void CreateShardPerCompany(Sharding sharding)
{
SqlConnectionStringBuilder connStrBldr = new SqlConnectionStringBuilder
{
UserID = SettingsHelper.AzureUsernamedb,
Password = SettingsHelper.AzurePasswordDb,
ApplicationName = SettingsHelper.AzureApplicationName,
DataSource = SettingsHelper.AzureSqlServer
};
UnitOfWork unitOfWork = new UnitOfWork();
ConfigurationDBDataContext context = new ConfigurationDBDataContext();
context.Empresas.Add(new Empresa()
{
Id = 1,
Nombre = "company name 1",
NIT = "873278423",
NombreRepresentanteLegal = "myself",
TelefonoRepresentanteLegal = "32894823",
NombreContacto = "myself",
TelefonoContacto = "32423"
});
context.SaveChanges();
var listofEmpresas = unitOfWork.EmpresaRepository.Get().ToList();
foreach(Empresa empresa in listofEmpresas)
{
DbUtils.CreateDatabaseIfNotExists(connStrBldr.ConnectionString, empresa.NIT);
sharding.RegisterNewShard(SettingsHelper.AzureSqlServer, empresa.NIT, connStrBldr.ConnectionString, empresa.Id);
}
}
}
}
the sharding.css
internal class Sharding
{
public ShardMapManager ShardMapManager { get; private set; }
public ListShardMap<int> ShardMap { get; private set; }
// Bootstrap Elastic Scale by creating a new shard map manager and a shard map on
// the shard map manager database if necessary.
public Sharding(string smmserver, string smmdatabase, string smmconnstr)
{
// Connection string with administrative credentials for the root database
SqlConnectionStringBuilder connStrBldr = new SqlConnectionStringBuilder(smmconnstr);
connStrBldr.DataSource = smmserver;
connStrBldr.InitialCatalog = smmdatabase;
// Deploy shard map manager.
ShardMapManager smm;
if (!ShardMapManagerFactory.TryGetSqlShardMapManager(connStrBldr.ConnectionString, ShardMapManagerLoadPolicy.Lazy, out smm))
{
this.ShardMapManager = ShardMapManagerFactory.CreateSqlShardMapManager(connStrBldr.ConnectionString);
}
else
{
this.ShardMapManager = smm;
}
ListShardMap<int> sm;
if (!ShardMapManager.TryGetListShardMap<int>("ElasticScaleWithEF", out sm))
{
this.ShardMap = ShardMapManager.CreateListShardMap<int>("ElasticScaleWithEF");
}
else
{
this.ShardMap = sm;
}
}
// Enter a new shard - i.e. an empty database - to the shard map, allocate a first tenant to it
// and kick off EF intialization of the database to deploy schema
// public void RegisterNewShard(string server, string database, string user, string pwd, string appname, int key)
public void RegisterNewShard(string server, string database, string connstr, int key)
{
Shard shard;
ShardLocation shardLocation = new ShardLocation(server, database);
if (!this.ShardMap.TryGetShard(shardLocation, out shard))
{
shard = this.ShardMap.CreateShard(shardLocation);
}
SqlConnectionStringBuilder connStrBldr = new SqlConnectionStringBuilder(connstr);
connStrBldr.DataSource = server;
connStrBldr.InitialCatalog = database;
// Go into a DbContext to trigger migrations and schema deployment for the new shard.
// This requires an un-opened connection.
using (var db = new ElasticScaleContext<int>(connStrBldr.ConnectionString))
{
// Run a query to engage EF migrations
(from b in db.Terceros
select b).Count();
}
// Register the mapping of the tenant to the shard in the shard map.
// After this step, DDR on the shard map can be used
PointMapping<int> mapping;
if (!this.ShardMap.TryGetMappingForKey(key, out mapping))
{
this.ShardMap.CreatePointMapping(key, shard);
}
}
}
In the code implementing database creation: DbUtils.CreateDatabaseIfNotExists() -- you are probably using a T-SQL CREATE DATABASE command to Create an Azure database on a logical server. Currently CREATE DATABASE doesn't support specifying the Pool -- however an update to Azure DB is expected within the next month that will extend the functionality of CREATE DATABASE and ALTER DATABASE to specify the Pool name as well.
In the meantime, you can make a REST API call from the CreateDatabaseIfNotExists() routine to add the database to the pool once it is created, using the Update SQL Database command: https://msdn.microsoft.com/en-us/library/azure/mt163677.aspx.
However, making a rest call from inside your c# can be complex, and is discussed here: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client . It may be simpler to wait for the upcoming support in the CREATE DATABASE command, which would require a very small modification within your CreateDatabaseIfNotExists() routine.

Refresh EntityFramework connection

I'm changing EntityFramework connection string in App.config like this:
var connectionString = new SqlConnectionStringBuilder(entityConnectionString.ProviderConnectionString);
connectionString.UserID = dbUser;
connectionString.Password = dbPass;
connectionString.InitialCatalog = dbCatalog;
connectionString.DataSource = dbServer;
entityConnectionString.ProviderConnectionString = connectionString.ToString();
cString.ConnectionString = entityConnectionString.ToString();
conf.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection("connectionStrings");
But EntityFramework continues to use an old connection settings until application restart. Is there any way to force EntityFramework to get new connection string from App.config?
I believe Travis is right. Here is code I've used to do this:
public void RefreshContext(string myConnectionString)
{
DisposeContext();
Context = new MyContext(myConnectionString);
}
public void DisposeContext()
{
if (Context == null)
return;
Context.Dispose();
}
Even if ConfigurationManager didn't cache stuff (though Save() might refresh the cache) the EntityFramework objects will cache the connection. In all likelyhood you need to release those objects and recreate them so it pulls the new connection string from configuration manager (assuming the cache gets refreshed) or actually modify the connection string on your DbContext object manually.

Entity Framework change connection at runtime

I have a web API project which references my model and DAL assemblies. The user is presented with a login screen, where he can select different databases.
I build the connection string as follows:
public void Connect(Database database)
{
//Build an SQL connection string
SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
{
DataSource = database.Server,
InitialCatalog = database.Catalog,
UserID = database.Username,
Password = database.Password,
};
//Build an entity framework connection string
EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
{
Provider = database.Provider,
Metadata = Settings.Default.Metadata,
ProviderConnectionString = sqlString.ToString()
};
}
First of all, how do I actually change the connection of the data context?
And secondly, as this is a web API project, is the connection string (set at login per above) persistent throughout the user's interaction or should it be passed every time to my data context?
A bit late on this answer but I think there's a potential way to do this with a neat little extension method. We can take advantage of the EF convention over configuration plus a few little framework calls.
Anyway, the commented code and example usage:
extension method class:
public static class ConnectionTools
{
// all params are optional
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new SqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.InitialCatalog = initialCatalog;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.DataSource = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
}
basic usage:
// assumes a connectionString name in .config of MyDbEntities
var selectedDb = new MyDbEntities();
// so only reference the changed properties
// using the object parameters by name
selectedDb.ChangeDatabase
(
initialCatalog: "name-of-another-initialcatalog",
userId: "jackthelady",
password: "nomoresecrets",
dataSource: #".\sqlexpress" // could be ip address 120.273.435.167 etc
);
I know you already have the basic functionality in place, but thought this would add a little diversity.
DbContext has a constructor overload that accepts the name of a connection string or a connection string itself. Implement your own version and pass it to the base constructor:
public class MyDbContext : DbContext
{
public MyDbContext( string nameOrConnectionString )
: base( nameOrConnectionString )
{
}
}
Then simply pass the name of a configured connection string or a connection string itself when you instantiate your DbContext
var context = new MyDbContext( "..." );
Jim Tollan's answer works great, but I got the Error: Keyword not supported 'data source'.
To solve this problem I had to change this part of his code:
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
to this:
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
{
ProviderConnectionString = new SqlConnectionStringBuilder(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString).ConnectionString
};
I'm really sorry. I know that I should't use answers to respond to other answers, but my answer is too long for a comment :(
The created class is 'partial'!
public partial class Database1Entities1 : DbContext
{
public Database1Entities1()
: base("name=Database1Entities1")
{
}
... and you call it like this:
using (var ctx = new Database1Entities1())
{
#if DEBUG
ctx.Database.Log = Console.Write;
#endif
so, you need only create a partial own class file for original auto-generated class (with same class name!) and add a new constructor with connection string parameter, like Moho's answer before.
After it you able to use parametrized constructor against original. :-)
example:
using (var ctx = new Database1Entities1(myOwnConnectionString))
{
#if DEBUG
ctx.Database.Log = Console.Write;
#endif
You can do this on-the-fly with an IDbConnectionInterceptor. This has the advantage of allowing you to work with a standard connection string and not the Entity Client version, and also not having to modify the auto-generated context classes in an EDMX model, or using overloaded constructors. It just works!
We use this, for instance, to replace a tokenized connection string with a password from a secrets vault.
First, implement the interface. I'm only showing one of the many interface methods that will need to be implemented. In this case, I'm implementing ConnectionStringGetting, and leaving all other method bodies empty:
public class SecretsDbConnectionInterceptor : IDbConnectionInterceptor
{
public void ConnectionStringGetting(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext)
{
var originalConnectionString = connection.ConnectionString;
try
{
connection.ConnectionString = /* Build your new connection string */;
}
catch (Exception e)
{
connection.ConnectionString = originalConnectionString;
Trace.WriteLine(e.Message);
}
}
// ... Many other methods here; leave them empty
}
You can wire this up via your .config file; just add an <interceptor /> to the existing <entityFramework /> node with your new inteceptor's fully qualified type name:
<entityFramework>
<interceptors>
<interceptor type="Foo.Bar.SecretsDbConnectionInterceptor, Foo.Bar" />
</interceptors>
...
</entityFramework>
Or, my personal preference, you can wire it up via code. It is equivalent to the config version. Ideally this would go in an Application_Startup in a service/UI project, or towards the top of Main in a console app, because it must run before you attempt to establish any new DbContexts:
DbInterception.Add(new Foo.Bar.SecretsDbConnectionInterceptor());
When you configure via code, you could pass parameters to your interceptor constructor, or use DI.
Note: the interceptor code runs every time you create a new instance of any DbContext in your application, so beware of performance impacts. You could implement some caching strategy within your interceptor, or make it a singleton instance with a context name/connection string mapping, or something smart like that.
Add multiple connection strings in your web.config or app.config.
Then you can get them as a string like :
System.Configuration.ConfigurationManager.
ConnectionStrings["entityFrameworkConnection"].ConnectionString;
Then use the string to set :
Provider
Metadata
ProviderConnectionString
It is better explained here :
Read connection string from web.config
string _connString = "metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=DATABASE;persist security info=True;user id=sa;password=YourPassword;multipleactiveresultsets=True;App=EntityFramework"";
EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(_connString);
ctx = new Entities(_connString);
You can get the connection string from the web.config, and just set that in the EntityConnectionStringBuilder constructor, and use the EntityConnectionStringBuilder as an argument in the constructor for the context.
Cache the connection string by username. Simple example using a couple of generic methods to handle adding/retrieving from cache.
private static readonly ObjectCache cache = MemoryCache.Default;
// add to cache
AddToCache<string>(username, value);
// get from cache
string value = GetFromCache<string>(username);
if (value != null)
{
// got item, do something with it.
}
else
{
// item does not exist in cache.
}
public void AddToCache<T>(string token, T item)
{
cache.Add(token, item, DateTime.Now.AddMinutes(1));
}
public T GetFromCache<T>(string cacheKey) where T : class
{
try
{
return (T)cache[cacheKey];
}
catch
{
return null;
}
}
In my case I'm using the ObjectContext as opposed to the DbContext so I tweaked the code in the accepted answer for that purpose.
public static class ConnectionTools
{
public static void ChangeDatabase(
this ObjectContext source,
string initialCatalog = "",
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "")
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? Source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new SqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.InitialCatalog = initialCatalog;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.DataSource = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
}
I wanted to have multiple datasources in the app config. So after setting up a section in the app.config i swaped out the datasource and then pass it into the dbcontext as the connection string.
//Get the key/value connection string from app config
var sect = (NameValueCollection)ConfigurationManager.GetSection("section");
var val = sect["New DataSource"].ToString();
//Get the original connection string with the full payload
var entityCnxStringBuilder = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["OriginalStringBuiltByADO.Net"].ConnectionString);
//Swap out the provider specific connection string
entityCnxStringBuilder.ProviderConnectionString = val;
//Return the payload with the change in connection string.
return entityCnxStringBuilder.ConnectionString;
This took me a bit to figure out. I hope it helps someone out. I was making it way too complicated. before this.
I have two extension methods to convert the normal connection string to the Entity Framework format. This version working well with class library projects without copying the connection strings from app.config file to the primary project. This is VB.Net but easy to convert to C#.
Public Module Extensions
<Extension>
Public Function ToEntityConnectionString(ByRef sqlClientConnStr As String, ByVal modelFileName As String, Optional ByVal multipleActiceResultSet As Boolean = True)
Dim sqlb As New SqlConnectionStringBuilder(sqlClientConnStr)
Return ToEntityConnectionString(sqlb, modelFileName, multipleActiceResultSet)
End Function
<Extension>
Public Function ToEntityConnectionString(ByRef sqlClientConnStrBldr As SqlConnectionStringBuilder, ByVal modelFileName As String, Optional ByVal multipleActiceResultSet As Boolean = True)
sqlClientConnStrBldr.MultipleActiveResultSets = multipleActiceResultSet
sqlClientConnStrBldr.ApplicationName = "EntityFramework"
Dim metaData As String = "metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string='{1}'"
Return String.Format(metaData, modelFileName, sqlClientConnStrBldr.ConnectionString)
End Function
End Module
After that I create a partial class for DbContext:
Partial Public Class DlmsDataContext
Public Shared Property ModelFileName As String = "AvrEntities" ' (AvrEntities.edmx)
Public Sub New(ByVal avrConnectionString As String)
MyBase.New(CStr(avrConnectionString.ToEntityConnectionString(ModelFileName, True)))
End Sub
End Class
Creating a query:
Dim newConnectionString As String = "Data Source=.\SQLEXPRESS;Initial Catalog=DB;Persist Security Info=True;User ID=sa;Password=pass"
Using ctx As New DlmsDataContext(newConnectionString)
' ...
ctx.SaveChanges()
End Using
For both SQL Server and SQLite Databases, use:
_sqlServerDBsContext = new SqlServerDBsContext(new DbContextOptionsBuilder<SqlServerDBsContext>().UseSqlServer("Connection String to SQL DB").Options);
For SQLite, make sure Microsoft.EntityFrameworkCore.Sqlite is
installed, then the connection string is simply "'DataSource='+ the file name".
_sqliteDBsContext = new SqliteDBsContext(new DbContextOptionsBuilder<SqliteDBsContext>().UseSqlite("Connection String to SQLite DB").Options);
well if you are working with EFCore, Then You can do something like to create a new connection string:
In Your Context File (For Sqlite)
public biorevContext(string connectionString) : base(GetOptions(connectionString))
{
this.Database.EnsureCreated();
}
private static DbContextOptions GetOptions(string connectionString)
{
return SqliteDbContextOptionsBuilderExtensions.UseSqlite(new DbContextOptionsBuilder(), connectionString).Options;
}
For MySql:
public biorevContext(string connectionString) : base(GetOptions(connectionString))
{
this.Database.EnsureCreated();
}
private static DbContextOptions GetOptions(string connectionString)
{
return MySQLDbContextOptionsExtensions.UseMySQL(new DbContextOptionsBuilder(), connectionString).Options;
}
For Sql:
public biorevContext(string connectionString) : base(GetOptions(connectionString))
{
this.Database.EnsureCreated();
}
private static DbContextOptions GetOptions(string connectionString)
{
return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}
and Then You can use it like this:
var context = new biorevContext("connectionString");
Linq2SQLDataClassesDataContext db = new Linq2SQLDataClassesDataContext();
var query = from p in db.SyncAudits orderby p.SyncTime descending select p;
Console.WriteLine(query.ToString());
try this code...

How to use a single connection string in whole winforms project

I am using Winforms, MySQL and C# in my project. In that I use a connection string in the app settings.
At each new page I will declare a connection string as public and use this string in the connection.
MySqlConnection connection = new MySqlConnection(MyConString);
I want to declare this MyConString only one time in the whole application. How to do this? Where to do?
I don't think you should expose your connection string to your Forms, they don't need to know that. You can encapsulate the creation of connections with a simple factory.
public class ConnectionFactory
{
public static MySqlConnection Create()
{
string connectionString = ConfigurationManager.AppSettings["..."];
MySqlConnection conection = new MySqlConnection(Config.ConnectionStr);
connection.Open();
return connection;
}
}
Then when you need a connection in a Form you can do:
private void button1_click(object sender, EventArg args)
{
using ( var connection = ConnectionFactory.Create() )
{
connection.Execute("...");
}
}
You can try something like the following:
public static class Config
{
public static string ConnectionStr = ConfigurationManager.AppSettings["..."];
}
You can then use it in your code
MySqlConnection connection = new MySqlConnection(Config.ConnectionStr);
Enterpise Library from Microsoft have great DataAccess part which beside other prtoblem solving and this one
You may have a separate class to handle databases and add the connection string as a field there. Each time you want to connect to the database, you may use that class. Also if you may use a property to access the string outside the class if you require.
Hope this helps...
The suggested approach is available at an MSDN article titled Storing and Retrieving Connection Strings. The following samples are slightly modified from this article.
After storing your connection string in an app.config file, you can retrieve all connection strings like so:
static void GetConnectionStrings()
{
var settings = ConfigurationManager.ConnectionStrings;
if (settings != null) {
foreach(ConnectionStringSettings cs in settings) {
Console.WriteLine(cs.Name);
Console.WriteLine(cs.ProviderName);
Console.WriteLine(cs.ConnectionString);
}
}
}
You could alternatively get the connection string by name:
// Returns null if the name is not found.
static string GetConnectionStringByName(string name)
{
string returnValue = null; // Assume failure.
var settings = ConfigurationManager.ConnectionStrings[name];
if (settings != null) {
returnValue = settings.ConnectionString;
}
return returnValue;
}
This also gives you the ability of Securing Connection Strings so that your database username & password are not embedded into your application assembly in clear-text.

Categories