[英]Which is more optimised code when using Dataset with or without Using() for Dispose
I use lot of Dataset
for my website so far i have been using Dataset
as 到目前为止,我一直在使用
Dataset
作为我的网站使用大量Dataset
Dataset
string strSql = "SELECT * FROM Articles";
DataSet ds = new DataSet();
ds = DataProvider.Connect_Select(strSql);
string Title = ds.Tables[0].Rows[0]["Article_Title"].ToString();
string Desc = ds.Tables[0].Rows[0]["Article_Desc"].ToString();
CODE with Using
block Using
块的代码
string strSql = "SELECT * FROM Articles";
// Create a DataSet in using statement.
using (DataSet ds = new DataSet())
{
ds = DataProvider.Connect_Select(strSql);
string Title = ds.Tables[0].Rows[0]["Article_Title"].ToString();
string Desc = ds.Tables[0].Rows[0]["Article_Desc"].ToString();
}
What is the best approach and optimized approach for using DataSet
使用
DataSet
的最佳方法和优化方法是什么
Above code i am using SQL
Statment otherwise i use Stored Procedures
上面的代码我正在使用
SQL
Statment,否则我使用Stored Procedures
using only ensures to call the Dispose method on the DataSet, even if the exception occurs. using only仅确保在DataSet上调用Dispose方法,即使发生异常也是如此。 Not sure about how much it is optimized but it is a safer approach and better practice for objects implementing
IDisposable
interface. 不确定它的优化程度,但对于实现
IDisposable
接口的对象来说,这是一种更安全的方法和更好的实践。 using statement is like try/finally block. using语句就像try / finally块。
Its like: 就像是:
DataSet ds;
try
{
ds = new DataSet();
ds = DataProvider.Connect_Select(strSql);
string Title = ds.Tables[0].Rows[0]["Article_Title"].ToString();
string Desc = ds.Tables[0].Rows[0]["Article_Desc"].ToString();
}
finally
{
if(ds != null)
ds.Dispose();
}
I would suggest that you use dapper. 我建议你使用短小精悍。 DataSet is quite inefficient.
DataSet效率很低。 Download Dapper, from Nuget or dapper.org
从Nuget或dapper.org下载Dapper
Creating a DTO (Data Transfer Object) 创建DTO(数据传输对象)
public class ArticleDto
{
public int ArticleID {get; set;}
public string Title {get; set;}
public string Description {get; set;}
}
Then you create in your data tier an base class that manages the connection to the database 然后在数据层中创建一个管理与数据库连接的基类
public abstract class SalesDb : IDisposable
{
protected static IDbConnection OpenConnection()
{
IDbConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["NAME"].ConnectionString);
connection.Open();
return connection;
}
}
Then, create your service class that return data from the database 然后,创建从数据库返回数据的服务类
public class ArticleService : SalesDb
{
public IEnumerable<ArticleDto> SelectAll()
{
using (IDbConnection connection = OpenConnection())
{
var articles = connection.Query<ArticleDto>("SELECT * FROM Articles");
return articles;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.