什么是使用LINQ to C#的最佳模式
public class CommonService
{
private readonly DataContext _context;
public CommonRepository()
{
_context = new DataContext();
}
public CommonRepository(DataContext context)
{
_context = context;
}
public List GetAll()
{
var query = from m in _context.MyModel
select m;
return m.ToList();
}
}
要么
public class CommonService
{
public List GetAll()
{
using (DataContext context = new DataContext())
{
var query = from m in context.MyModel
select m;
return m.ToList();
}
}
}
或者你有更多的模式,请给我建议。
这里有一个主要区别:第一个代码示例在服务的整个生命周期内保留单个DataContext,而第二个示例为每个操作创建一个新的。 第二个例子通常是正确的,因为使用Change Tracking,DataContext可以变得非常庞大,而且如果别的方法调用了SubmitChanges() ,你可以意外提交你不想提交的东西。
查看Linq to SQL DataContext的多个/单个实例
您可以使用这两种模式,但始终确保上下文寿命较短。 第一个选项允许您在CommonService中创建需要上下文的方法,但无需在每个方法中创建一个方法。 所以它可以防止重复的代码。 此外,它允许IoC容器通过构造函数注入将一个上下文注入CommonService 。
如果你选择第一个选项(我倾向于这样做),你可以考虑让CommonService实现IDisposable ,给它一个Dispose上下文的Dispose方法。 这也会鼓励您在using构造中使用CommonService ,从而限制其使用寿命。
