Is this ok for using EntityFramework context
In my DAL, I'm currently using this in a base class:
protected static MyCMSEntities MyCMSDb
{
get { return new MyCMSEntities(ConfigurationManager.ConnectionStrings["MyCMSEntities"].ConnectionString); }
}
and calling like this from a subclass:
public static bool Add(ContentFAQ newContent)
{
MyCMSEntities db = MyCMSDb;
newContent.DateModified = DateTime.Now;
newContent.OwnerUserId = LoginManager.CurrentUser.Id;
db.ContentFAQ.AddObject(newContent);
return db.SaveChanges() > 0;
}
I understand the method to get the context is static, but as it creates a new intance of the context, this is not static, i.e. it is new for each call to the Add method.
Am I correct and more importantly, ok for a web application?
开发者_如何转开发Thanks.
You are correct in using a new context for every web call - but why this obfuscation? I would recommend removing this indirection with the static property (makes the code harder to understand) and also using a using
block since the context is disposable:
public static bool Add(ContentFAQ newContent)
{
using(var db = new MyCMSEntities())
{
newContent.DateModified = DateTime.Now;
newContent.OwnerUserId = LoginManager.CurrentUser.Id;
db.ContentFAQ.AddObject(newContent);
return db.SaveChanges() > 0;
}
}
Also the default constructor of the context should use the default connection string, which is the right one if you didn't change it in your configuration (otherwise just add it back in).
精彩评论