0

根据asp.net 上的本教程,它显示了以下代码:

using System;
using ContosoUniversity.Models;

namespace ContosoUniversity.DAL
{
    public class UnitOfWork : IDisposable
    {
        private SchoolContext context = new SchoolContext();
        private GenericRepository<Department> departmentRepository;
        private GenericRepository<Course> courseRepository;

        public GenericRepository<Department> DepartmentRepository
        {
            get
            {

                if (this.departmentRepository == null)
                {
                    this.departmentRepository = new GenericRepository<Department>(context);
                }
                return departmentRepository;
            }
        }

        public GenericRepository<Course> CourseRepository
        {
            get
            {

                if (this.courseRepository == null)
                {
                    this.courseRepository = new GenericRepository<Course>(context);
                }
                return courseRepository;
            }
        }

        public void Save()
        {
            context.SaveChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

每次我想添加一个新的数据库表时都必须编写代码吗?例如,如果我想添加一个 StudentsRepository,我必须这样做(?):

private GenericRepository<Student> studentRepository;

public GenericRepository<Student> StudentRepository
{
    get
    {

        if (this.studentRepository == null)
        {
            this.studentRepository = new GenericRepository<Student>(context);
        }
        return studentRepository;
    }
}

如果我的数据库有 50 个表怎么办?我是否必须为所有 50 个代码编写此代码!?

4

1 回答 1

0

您的问题的答案是“是”,工作单元应包含访问所有可能存储库的属性。

如果编写代码让您感到困扰,请创建一个 T4 模板并让该类自动生成。

于 2013-09-16T16:42:45.197 回答