我是第一次编写自己的数据访问层类,所以我想将它包装在(使用)括号内,但这需要类实现Idisposable。
我唯一放在那里的是
conn.close()
还有什么遗漏我应该添加吗?
课程概述:
public class DAL : IDisposable
{
SqlConnection conn;
SqlCommand cmd;
SqlTransaction transaction;
public int Status = 1;
public DAL()
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString);
conn.Open();
}
public void InsertRequest(UserAndRequestInfo UInfo, UserCrops UCrop)
{
}
public void InsertBGs(BreedingGroups BG)
{
}
public void EndTransaction()
{
if (Status == 1)
transaction.Commit();
if (Status < 0)
transaction.Rollback();
}
public void EndConnection()
{
conn.Close();
}
void Dispose()
{
conn.Close();
}
来自:
using (DAL db = new DAL())
{
foreach (var crop in UInfo.UserCropInfo)
{
db.InsertRequest(UInfo, crop);
foreach (BreedingGroups bg in crop.BGs)
{
db.InsertBGs(bg);
}
db.EndTransaction();
}
db.EndConnection(); <---- //If 'using' is there I'll remove this line
}
此外,在这种特殊情况下,调用db.EndConnection()方法不会更好
答案 0 :(得分:4)
是:在班上的任何一次性变量上调用Dispose()
。
void Dispose()
{
if(cmd != null)
cmd.Dispose();
if(transaction != null)
transaction.Dispose();
if(conn != null)
conn.Dispose();
}
编辑:conn.Dispose()
也会调用conn.Close()
,因此如果您调用dispose,则无需再调用它。
答案 1 :(得分:0)
这对您来说只是一个选择,使用 InsertRequest 方法中的使用范围代替如下:
public class DAL
{
public void InsertRequest(UserAndRequestInfo UInfo, UserCrops UCrop)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
{
conn.Open();
SqlCommand command = conn.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = conn.BeginTransaction("SampleTransaction");
command.Connection = conn;
command.Transaction = transaction;
try
{
command.CommandText = "Insert into ...";
command.ExecuteNonQuery();
command.CommandText = "Insert into ...";
command.ExecuteNonQuery();
// Attempt to commit the transaction.
transaction.Commit();
}
catch (Exception ex)
{
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
public void InsertBGs(BreedingGroups BG)
{
}
}
请注意,您不需要在Constructure中建立数据库连接,将其删除。 并使用相同的概念来实现 InsertBGs 方法。 这是调用
的形式DAL db = new DAL();
foreach (var crop in UInfo.UserCropInfo)
{
db.InsertRequest(UInfo, crop);
foreach (BreedingGroups bg in crop.BGs)
{
db.InsertBGs(bg);
}
}