使用 EntityFramework 上下文可以吗
在我的 DAL 中,我目前在基类中使用它:
protected static MyCMSEntities MyCMSDb
{
get { return new MyCMSEntities(ConfigurationManager.ConnectionStrings["MyCMSEntities"].ConnectionString); }
}
并从子类中这样调用:
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;
}
我知道获取上下文的方法是静态的,但当它创建上下文的新实例时,这不是静态的,即每次调用 Add 方法时它都是新的。
我是否正确,更重要的是,对于网络应用程序来说可以吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您为每个网络调用使用新的上下文是正确的 - 但为什么要这样混淆呢?我建议使用静态属性删除此间接寻址(使代码更难理解),并使用
using
块,因为上下文是一次性的:上下文的默认构造函数也应使用默认连接字符串,如果您没有在配置中更改它,则这是正确的(否则只需将其添加回来)。
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: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).