根据asp.net上的this tutorial,它会显示以下代码:
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个人编写此代码!?
答案 0 :(得分:0)
您的问题的答案是“是”,工作单元应包含访问所有可能存储库的属性。
如果您无法编写代码,请创建一个T4模板并自动生成该类。