I am creating xunit test with EF Core 2.0.0 and InMemory 2.0.0. I noticed that the entities are not being added in the context. However it is being added at context..Local
Below is the snippet of the code
public UnitOfWorkTest()
{
_appointment = new Appointment
{
AppointmentType = AppointmentTypes.EyeTest,
AppProgress = Appointment.Confirmed,
BranchIdentifier = "MEL",
DateAdded = DateTime.Now,
Duration = 30,
Resid = "KAI",
};
}
public MyDbContext InitContext()
{
var options = new DbContextOptionsBuilder<MyDbContext>()
.UseInMemoryDatabase("Add_writes_to_database")
.Options;
return new MyDbContext(options);
}
public async Task UnitOfWork_Transaction_Test()
{
using (var context = InitContext())
{
using (var unitOfWork = new UnitOfWork(context))
{
context.Appointment.Add(_appointment);
await unitOfWork.Commit();
Assert.True(context.Appointment.Local.Count == 1);
}
}
}
Unit of Work
public sealed class UnitOfWork : IUnitOfWork
{
private IDbContext _dbContext;
public UnitOfWork(IDbContext context)
{
_dbContext = context;
}
public async Task<int> Commit()
{
// Save changes with the default options
return await _dbContext.SaveChangesAsync();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_dbContext != null)
{
_dbContext.Dispose();
_dbContext = null;
}
}
}
}
IDbContext
public interface IDbContext : IDisposable
{
DbSet<TEntity> Set<TEntity>() where TEntity : class;
EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
EntityEntry Entry(object entity);
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken));
}
context.Appointment
always return empty list/null but I can see the added entity in context.Appointment.Local
Any idea why this happens? How do I get the entity added in Appointment collection and not in Appointment.Local collection?
After this line
context.Appointment.Add(_appointment);
try to save changes in your contextcontext.SaveChanges()
.I hope it will help.