【发布时间】:2011-08-02 18:29:41
【问题描述】:
我正在尝试使用 this Scott Allen tutorial 实现 UnitofWork 模式
我当前的 SqlUnitOfWork 如下
public class SqlUnitOfWork : IUnitOfWork {
public SqlUnitOfWork() {
var connectionString =
ConfigurationManager
.ConnectionStrings[ConnectionStringName]
.ConnectionString;
_context = new ObjectContext(connectionString);
_context.ContextOptions.LazyLoadingEnabled = true;
}
public IRepository<PhysicalTest> PhysicalTests
{
get {
if (_physicalTests == null)
{
_physicalTests = new SqlRepository<PhysicalTest>(_context);
}
return _physicalTests;
}
}
public IRepository<EHR> EHRs
{
get
{
if (_EHRs == null)
{
_EHRs = new SqlRepository<EHR>(_context);
}
return _EHRs;
}
}
public void Commit() {
_context.SaveChanges();
}
SqlRepository<PhysicalTest> _physicalTests = null;
SqlRepository<EHR> _EHRs = null;
readonly ObjectContext _context;
const string ConnectionStringName = "default";
}
我当前的连接字符串如下
<add name="default" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;MultipleActiveResultSets=True; initial catalog=MyAppDB" providerName="System.Data.SqlClient" />
还值得指出的是,我的控制器使用通过 mvcscaffolding 创建的控制器工作正常,但工作单元(由于某种原因需要一个连接字符串作为参数,而不是仅使用 MyAppDBContext() 实例)不起作用。
当我尝试使用以下代码在控制器中调用操作时遇到的错误:
public class PhysicalTestsController : Controller
{
private IUnitOfWork unitOfWork;
private IRepository<EHR> ehrRepository;
public PhysicalTestsController(IUnitOfWork unit)
{
unitOfWork = unit;
ehrRepository = unitOfWork.EHRs;
}
public ActionResult Index(int ehrId, int? page)
{
EHR ehr = ehrRepository.FindById(ehrId);
if (ehr.UserName != User.Identity.Name)
return View("Invalid Owner");
const int pageSize = 5;
var physicaltests = ehr.PhysicalTests.OrderByDescending(test => test.CreationDate);
List<PhysicalTestListItem> physicalTestsVM = new List<PhysicalTestListItem>();
Mapper.Map(physicaltests, physicalTestsVM);
var paginatedTests = new PaginatedList<PhysicalTestListItem>(physicalTestsVM, page ?? 0, pageSize);
return View(paginatedTests);
}
}
是这个吗
【问题讨论】:
标签: entity-framework repository repository-pattern unit-of-work