我正在测试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
}
BaseRepository
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>
{
}
答案 0 :(得分:1)