作为我在所有业务应用程序中使用的常用实用程序的一部分,我有这段代码...
using System.Web.UI.WebControls;
public class Database
{
/// <summary>
/// Creates a DataView object using the provided query and an SqlDataSource object.
/// </summary>
/// <param name="query">The select command to perform.</param>
/// <returns>A DataView with data results from executing the query.</returns>
public static DataView GetDataView(string query)
{
SqlDataSource ds = GetDBConnection();
ds.SelectCommand = query;
DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
return dv;
}
/// <summary>
/// Creates a SqlDataSource object with initialized connection string and provider
/// </summary>
/// <returns>An SqlDataSource that has been initialized.</returns>
public static SqlDataSource GetDBConnection()
{
SqlDataSource db = new SqlDataSource();
db.ConnectionString = GetDefaultConnectionString(); //retrieves connection string from .config file
db.ProviderName = GetDefaultProviderName(); //retrieves provider name from .config file
return db;
}
}
然后,在我的项目中,为了从数据库中检索数据,我将使用一些代码,例如......
DataView dv=Database.GetDataView("select mycolumn from my table");
//loop through data and make use of it
我因以这种方式使用 SqlDataSource 而受到一些人的批评。人们似乎不喜欢我纯粹通过代码使用 Web 控件,而不是将其放在 ASPX 页面上。他们看起来不太对劲,但他们没能告诉我缺点。那么,有缺点吗?这是我的主要问题。因为如果有很多缺点,我可能不得不改变我开发的许多内部应用程序的方式。
我的数据库类甚至可以在非 ASP.NET 情况下工作,只要我添加 System.Web 程序集。我知道包大小略有增加,但我觉得对于我正在编写的应用程序类型来说这是值得的。从 WPF/Windows Forms/Console 程序中使用 SqlDataSource 有缺点吗?
最佳答案
好吧,没有硬性规定阻止任何人进行此类实现。
但是,在执行该实现之前需要回答以下几个问题。
- 这种用法线程安全吗? (因为多个消费应用程序很可能会发出相同的调用。
- 是否会有分层差异化(在数据层中使用 UI.Control)?
- 如果该控件在下一个框架版本中变得过时/受限怎么办?
关于c# - 在非控制情况下使用 SqlDataSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20668746/