【发布时间】:2010-10-30 18:42:30
【问题描述】:
我正在尝试更好地处理解耦我的代码、代码重用等。
每次我想阅读一些行时,我都厌倦了输入以下内容:
using(SqlConnection conn = new SqlConnection(myConnString))
{
using(SqlCommand cmd = new SqlCommand(cmdTxt, conn))
{
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
/* do something with rows */
}
}
}
}
我知道有 LINQ to SQL(我不喜欢它)和实体框架(还是个婴儿)。我不必输入我的查询没有问题,我只是不想每次都输入命令构造、行迭代器等。
我环顾四周,发现了一些我认为对我有用的东西,并尝试实施它以使事情变得更容易。正如您在评论中看到的,我收到 SqlDataReader 已关闭的错误。我猜这可能是因为 DataFactory.ExecuteReader() 方法中的 using 语句。返回阅读器时,对我的 SqlConnection 和 SqlCommand 变量调用 dispose 方法。我在吗?如果是这样,应该如何管理连接和命令变量?
编辑:我更新了我的代码示例以更好地反映我在做什么。
public class DataFactory
{
public DataFactory()
{}
public DataFactory(string connectionString)
{
_connectionString = connectionString;
}
protected _connectionString = "Data Source=Localhost, etc, etc";
private string ConnectionString
{
get{return _connectionString;}
}
public SqlConnection GetSqlConnection()
{
return new SqlConnection(ConnectionString);
}
public SqlDataReader ExecuteReader(string cmdTxt)
{
using(SqlConnection conn = new SqlConnection(ConnectionString))
{
using(SqlCommand cmd = new SqlCommand(cmdTxt, conn))
{
conn.Open();
return cmd.ExecuteReader();
}
}
}
}
public IRepository<T>
{
T GetById(int id);
}
public MyTypeRepository: IRepository<MyType>
{
private static DataFactory _df = new DataFactory();
public MyType GetById(int id)
{
string cmdTxt = String.Format("SELECT Name FROM MyTable WHERE ID = {0}", id);
using(SqlDataReader rdr = _df.ExecuteReader(cmdTxt))
{
if(rdr.Read()) /* I get an error that the reader is already closed here */
{
return new MyType(
Convert.ToInt32(rdr["Id"]),
rdr["Name"]);
}
else
{
return null;
}
}
}
}
public class MyType
{
public MyType(int id, string name)
{
_id = id;
_name = name;
}
private string _name;
public string Name
{
get{return _name;}
}
private int _id;
public int Id
{
get{return _id;}
}
public override void ToString()
{
return string.Format("Name: {0}, Id: {1}", Name, Id);
}
}
public class Program
{
private static MyTypeRepository _mtRepo = new MyTypeRepository();
static void Main()
{
MyType myType = _mtRepo.GetById(1);
Console.WriteLine(myType.ToString());
}
}
我也想知道我正在做的事情是否有意义,或者,如果没有,如何实现类似的东西,这样我就不必经常输入连接创建等。
【问题讨论】:
-
好吧 linq-2-sql 让调用存储过程变得非常简单,我猜每个人都有自己的想法。
标签: c# data-access-layer