1

我正在测试 EF CodeFirst CTP5 并试图实现工作单元和存储库模式。但是当我运行一个简单的测试时,我得到:

System.InvalidOperationException :实体类型 Log 不是当前上下文模型的一部分。

数据库获取由 EF 创建,当我调用 .Add() 时失败。似乎没有使用相同的上下文,但我不知道为什么?

希望有聪明人来救我!
提前感谢您抽出宝贵时间。

这是一些代码:

日志小屋上下文

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,现在只是从基础派生

public interface ILogRepository : IBaseRepository<Log>
{
}
4

1 回答 1

1

在这里回答:Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable

于 2010-12-21T23:18:16.553 回答