我正在为应用程序编写数据访问层.访问层广泛使用linq类来返回数据.目前,为了将数据反映回数据库,我添加了一个私有数据上下文成员和一个公共保存方法.代码看起来像这样:
private DataContext myDb;
public static MyClass GetMyClassById(int id)
{
DataContext db = new DataContext();
MyClass result = (from item in db.MyClasss
where item.id == id
select item).Single();
result.myDb = db;
return result;
}
public void Save()
{
db.SubmitChanges();
}
Run Code Online (Sandbox Code Playgroud)
这是一个粗略的过度简化,但它给出了一般的想法.有没有更好的方法来处理这种模式?每次我想访问数据库时,我是否应该实例化新的数据上下文?
我经常使用看起来像这样的模式.我想知道这是否正常,或者是否有最佳实践我不在这里申请.
具体来说,我在想; 在抛出异常的情况下,我在finally块中的代码足以确保连接被正确关闭?
public class SomeDataClass : IDisposable
{
private SqlConnection _conn;
//constructors and methods
private DoSomethingWithTheSqlConnection()
{
//some code excluded for brevity
try
{
using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection))
{
_SqlConnection.Open();
countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());
}
}
finally
{
//is this the best way?
if (_SqlConnection.State == ConnectionState.Closed)
_SqlConnection.Close();
}
//some code excluded for brevity
}
public Dispose()
{
_conn.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud) 我在我的项目中使用Linq-To-Entity.但是,我在使用Stored Procedure或LINQ to Table or View在某些情况下犹豫不决.不过,我一般喜欢使用LINQ,因为的普莱语法.我搜索过谷歌,但没有找到详细的问题.
我们考虑一下这段代码:
using (NorthwindEntities db = new NorthwindEntities())
{
var custs = from c in db.Customers where c.City == "London" select c;
var edus = from c in db.Educations where c.Education != "2" select c;
// ... and so on
}
Run Code Online (Sandbox Code Playgroud)
问题:
1.它是否为每个查询打开一个新连接?如果是,那么不建议单独使用上述查询?
2.另外,你能否告诉我有什么情况我必须使用存储过程而不是LINQ?