【发布时间】:2023-03-13 17:23:01
【问题描述】:
我正在使用 EF Core 2.0.0 和 InMemory 2.0.0 创建 xunit 测试。我注意到实体没有被添加到上下文中。但是它被添加到 context..Local
下面是sn-p的代码
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);
}
}
}
工作单元
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 总是返回空列表/null 但我可以在context.Appointment.Local 中看到添加的实体
知道为什么会这样吗?如何将实体添加到 Appointment 集合中而不是 Appointment.Local 集合中?
【问题讨论】:
-
你能展示你的 UnitOfWork 课程吗?你的 unitOfWork.Commit() 是什么?
-
@hugorgor 我已经编辑了问题
-
你能把“new UnitOfWork”周围的“using”去掉吗?
-
仍然有同样的问题
标签: c# entity-framework .net-core xunit.net entity-framework-core