MVC3 数据上下文最佳实践
这是我在控制器中执行的操作。在此控制器内部创建和处置数据库连接(即 PhotoGalleryContext - 这是与 MySql 数据库的连接)而不是通过在模型的数据访问层中完成此操作来进行抽象,是否被认为是不好的做法。 cs课?
// GET: /Admin/GetPhoto/id
public ActionResult GetPhoto(int id)
{
PhotoGalleryContext db = new PhotoGalleryContext();
Models.PhotoGallery.Photo photo = new Models.PhotoGallery.Photo();
photo = db.Photos.Where(p => p.PhotoId == id).Single();
string filePath = photo.FileLocation;
db.Dispose();
byte[] byteArray;
try
{
byteArray = System.IO.File.ReadAllBytes(filePath);
return File(byteArray, "image/jpg");
}
catch (Exception)
{
//throw;
}
return null;
}
This is an action I have in my controller. Is it considered bad practice to be creating and disposing a database connection (i.e. PhotoGalleryContext - which is a connection to a MySql database) inside of this controller as opposed to having an abstraction by having this action done in a data access layer in a model .cs class?
// GET: /Admin/GetPhoto/id
public ActionResult GetPhoto(int id)
{
PhotoGalleryContext db = new PhotoGalleryContext();
Models.PhotoGallery.Photo photo = new Models.PhotoGallery.Photo();
photo = db.Photos.Where(p => p.PhotoId == id).Single();
string filePath = photo.FileLocation;
db.Dispose();
byte[] byteArray;
try
{
byteArray = System.IO.File.ReadAllBytes(filePath);
return File(byteArray, "image/jpg");
}
catch (Exception)
{
//throw;
}
return null;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在做出决定时,您可能会考虑应用程序的大小。我想说分离模型是最佳实践,但对于较小的应用程序,也许您应该将
PhotoGalleryContext
包装在 using 块中:You would probably consider the size of your application when deciding this. I would say separating the model is a best practice, but for smaller apps, maybe you should just wrap the
PhotoGalleryContext
in a using block:同意大卫的观点,因为这取决于您的应用程序的大小。
但是,我建议使用依赖注入来为您管理连接。
使用诸如 StructureMap 之类的东西,您可能会得到如下所示的内容:
翻译为:
这样,StructureMap 将自动为您打开/关闭连接。
然后你的控制器看起来像这样:
在你的操作方法中,
_db
将准备好为你服务。只需几行代码即可在应用程序中节省大量重复的 using 语句。
Agree with David, in that it depends on the size of your application.
However, i would suggest to use dependency injection to manage the connection for you.
Using something like StructureMap, you could have something like this:
Which translates to:
That way, StructureMap will automatically open/close the connection for you.
Then your controller can look like this:
And in your action methods,
_db
will be ready to go for you.Few lines of code to save a lot of repetitive using statements across your application.