I'm testing the EF CodeFirst CTP5 and was trying to implement The Unit Of Work and Repository patterns. But when I run a simple test I get:
System.InvalidOperationException : The entity type Log is not part of the model for the current context.
The Database get's created by the EF and it fails when I call .Add() It seems that the same context is not being used but I can't figure out why?
Hoping for some smart human coming to rescue me!
Thanks in advance for taking your time.
Here is some code:
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, using Ninject to build the context, this works since I creates the DB
[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, just derives from base for now
public interface ILogRepository : IBaseRepository<Log>
{
}