继续处理并增加某些方法的 CommandTimeout

Keep disposing and increase CommandTimeout for some methods

我想去掉重复的代码行:

context.Database.CommandTimeout = 180;

这是我的存储库 class:

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);
        }
        
    }
}

我认为 I can do it like that:

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();          
    }
}

但是,在我看来,这种方法并不好,因为它不会关闭数据库连接。这种方法不处理任何资源。

不希望增加整个 Entity Framework 个实体的超时。为此 class.

增加超时是必要的

是否可以摆脱重复代码并继续处理?

只需在 DbContext 的构造函数中设置 CommandTimeout

public MyDbContext() : base()
{
  this.Database.CommandTimeout = 180;
}

或者将 GetDbContext() 方法添加到您的 StudentRepo

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);
        }
        
    }
}