问题描述
我想去掉重复的代码行:
context.Database.CommandTimeout = 180;
这是我的存储库类:
public class StudentRepository : IStudentRepository
{
public IEnumerable<Student> GetStudents()
{
using (var context = new SchoolContext())
{
context.Database.CommandTimeout = 180; // repeat 1
return context.Students.ToList();
}
}
public void InsertStudents(IEnumerable<Student> students)
{
using (var context = new SchoolContext())
{
context.Database.CommandTimeout = 180; // repeat 2
context.Students.AddRange(students);
context.SaveChanges();
}
}
public Student GetStudentByID(int id)
{
using (var context = new SchoolContext())
{
return context.Students.Find(id);
}
}
}
public class StudentRepository : IStudentRepository
{
private SchoolContext context;
public StudentRepository(SchoolContext context)
{
this.context = context;
this.context.Database.CommandTimeout = 180;
}
public IEnumerable<Student> GetStudents()
{
return context.Students.ToList();
}
public void InsertStudents(IEnumerable<Student> students)
{
context.SaveChanges();
}
}
但是,在我看来,这种方法并不好,因为它不会关闭数据库连接。这种方法不处理任何资源。
增加整个实体框架实体的超时时间是不可取的。这个类只需要增加超时时间。
是否有可能摆脱重复代码并继续处理?
解决方法
只需在 DbContext 的构造函数中设置 CommandTimeout
public MyDbContext() : base()
{
this.Database.CommandTimeout = 180;
}
或者在你的 StudentRepo 中添加一个 GetDbContext() 方法
public class StudentRepository : IStudentRepository
{
private SchoolContext GetDbContext()
{
var db = new SchoolContext();
db.Database.CommandTimeout = 180;
return db;
}
public IList<Student> GetStudents()
{
using (var context = GetDbContext())
{
return context.Students.ToList();
}
}
public void InsertStudents(IEnumerable<Student> students)
{
using (var context = GetDbContext())
{
context.Students.AddRange(students);
context.SaveChanges();
}
}
public Student GetStudentByID(int id)
{
using (var context = GetDbContext())
{
return context.Students.Find(id);
}
}
}