I would like to know if it’s a good practice to create a static class to get the Entity Database Context.
ThisGetEntity() return the Context. In the GetEntity method, I have a dynamic connection.
When someone go to my login page, they need to provide a database number + Username + Password. I stock the dbname in Session["DBName"].
public static class EntityFactory
{
public static DBEntities GetEntity()
{
var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = ConfigurationManager.AppSettings["DataSource"];
scsb.InitialCatalog = "db1";
scsb.MultipleActiveResultSets = true;
scsb.IntegratedSecurity = true;
if (HttpContext.Current.Session["DBName"] == null)
{
HttpContext.Current.Response.Redirect("/Account/Step1");
}
else
{
scsb.InitialCatalog = HttpContext.Current.Session["DBName"].ToString();
}
var builder = new EntityConnectionStringBuilder();
builder.Metadata = "res://*/nms.bin.Models.DBModel.csdl|res://*/nms.bin.Models.DBModel.ssdl|res://*/nms.bin.Models.DBModel.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = scsb.ConnectionString;
DBEntities db = new DBEntities(builder.ConnectionString);
return db;
}
When I want to get the DBContext by example in a controler, I Just need to do EntityFactory.GetEntity() and that returns me a DB context.
- Is it Correct the way I do this
- Is that could be a problem if 20 clients log at the same time but with a different dbname.
- For the moment, I’m not using any dispose, Is it a problem? Based on my
EntityFactoryClass, can I make a global disposable in that class that will be call automaticly. (I think about the descrutor method).
in order :
You can improve it by passing to
GetEntity()all the info it needs (like the dbname, username and password). As it is now the static method is tightly coupled with the session. Move the session out from the method.It should not as the Session is per user.
If
DBEntitiesinherits fromDbContextyou can call the Dispose after you’ve used the object. Es:dbEntitiesObj.Dispose();