【发布时间】:2010-12-20 08:38:37
【问题描述】:
我正在测试 EF CodeFirst CTP5 并尝试实现工作单元和存储库模式。但是当我运行一个简单的测试时,我得到:
System.InvalidOperationException : 实体类型 Log 不是当前上下文模型的一部分。
数据库获取由 EF 创建,当我调用 .Add() 时它失败 似乎没有使用相同的上下文,但我不知道为什么?
希望有聪明人来救我!
提前感谢您抽出宝贵时间。
这里有一些代码:
LogCabinContext
public class LogCabinContext : DbContext, IUnitOfWork
{
public LogCabinContext() { }
public LogCabinContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
#region IUnitOfWork Members
public void Save()
{
base.SaveChanges();
}
#endregion
}
基础存储库
public class BaseRepository<T> : IBaseRepository<T> where T : EntityBase
{
public LogCabinContext _unitOfWork;
private DbSet<T> _dbSet;
public BaseRepository(IUnitOfWork unitOfWork)
{
if (unitOfWork == null)
throw new NullReferenceException("UnitOfWork must not be null");
_unitOfWork = unitOfWork as LogCabinContext;
_dbSet = _unitOfWork.Set<T>();
}
#region IBaseRepository Members
public T GetById(int id)
{
return _dbSet.SingleOrDefault(x => x.Id == id);
}
public void Add(T entity)
{
_dbSet.Add(entity);
}
public void Delete(T entity)
{
_dbSet.Remove(entity);
}
public IEnumerable<T> List()
{
return _dbSet.OrderBy(x => x.Id).AsEnumerable();
}
public IUnitOfWork CurrentUnitOfWork
{
get { return _unitOfWork; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
_unitOfWork.Dispose();
}
#endregion
}
SimpleTest,使用 Ninject 构建上下文,因为我创建了数据库,所以这个工作正常
[TestFixture]
public class LogRepositoryTests
{
IKernel _kernel;
[SetUp]
public void SetUp()
{
_kernel = new StandardKernel(new DatabaseModule());
}
[TearDown]
public void TearDown()
{
_kernel.Dispose();
}
public ILogRepository GetLogRepository()
{
ILogRepository logRepo = _kernel.Get<ILogRepository>();
return logRepo;
}
[Test]
public void Test()
{
using (ILogRepository repo = this.GetLogRepository())
{
Log myLog = new Log();
myLog.Application = "Test";
myLog.Date = DateTime.Now;
myLog.Exception = "Exception message";
myLog.Machinename = "local";
myLog.Message = "Testing";
myLog.Stacktrace = "Stacktrace";
repo.Add(myLog);
}
}
}
ILogRepository,现在只是从base派生
public interface ILogRepository : IBaseRepository<Log>
{
}
【问题讨论】:
-
我的应用程序中遇到了类似的异常。找到原因了吗?
标签: .net ef-code-first