In Memory Database with.Net Core not adding data to entity collection

2.4k Views Asked by At

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?

2

There are 2 best solutions below

1
On

After this line context.Appointment.Add(_appointment); try to save changes in your context context.SaveChanges().I hope it will help.

0
On

In-memory database is faking a test double. Your current test relies on the implementation details of "DbSet<T> properties" within this test double.

I think implementation details is the answer to why Set<T>() works inplace:

Assert.True(context.Set<Appointment>().Count == 1);

DbSet<T> properties are there for convenience, rather than to implement data access. It is not even obligatory to have - all of - them in the context class (until you provide navigation properties in entity classes).

You can also check: Using DbContext Set<T>() instead of exposing on the context for clarification.