gpt4 book ai didi

c# - 声明数据库变量的良好做法

转载 作者:太空狗 更新时间:2023-10-30 00:24:55 26 4
gpt4 key购买 nike

大多数时候,当我处理与数据库相关的对象时,我是这样工作的:

// Declare a private static variable of my database
private static BlueBerry_MTGEntities mDb = new BlueBerry_MTGEntities();

然后,在任何方法(示例)中:

public StoreInfo GetStoreByID(int _storeID)
{
using (mDb = new BlueBerry_MTGEntities())
{
mDb.Database.Connection.Open();

// Bla bla stuff to return the proper StoreInfo Object.
}
}

以这种方式工作以避免池崩溃和开发高效的 MVC Asp.Net 应用程序是否是一种好的做法?如果不是,好的做法是什么?您会怎么做?

最佳答案

如果要在 using 语句中使用它,则不必(甚至声明它) 实例化它。

public StoreInfo GetStoreByID(int _storeID)
{
using (BlueBerry_MTGEntities mDb = new BlueBerry_MTGEntities())
{
mDb.Database.Connection.Open();

// Bla bla stuff to return the proper StoreInfo Object.
}
}

如果您打算在 using 语句之外使用 mDb,那么您只需声明它,而不必实例化它(使用 new 关键字)

关于c# - 声明数据库变量的良好做法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20640873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com