关于这个答案,我试图通过设置UseInMemoryDatabase相同的名称来使多个上下文正常工作。下面的测试失败,第二个上下文为空。
我还需要做什么才能在内存数据库中共享相同的内容?
[Test]
public void MultipleContextTest()
{
var firstContext = new FirstContext(new DbContextOptionsBuilder<FirstContext>().UseInMemoryDatabase("DB").Options);
firstContext.Add(new Entity() {Name = "Test"});
firstContext.SaveChanges();
var secondContext = new SecondContext(new DbContextOptionsBuilder<SecondContext>().UseInMemoryDatabase("DB").Options);
Assert.AreEqual(1, secondContext.Entity.Count());
}
public class FirstContext : DbContext
{
public DbSet<Entity> Entity { get; set; }
public FirstContext(DbContextOptions options) : base(options)
{
}
}
public class SecondContext : DbContext
{
public DbSet<Entity> Entity { get; set; }
public SecondContext(DbContextOptions options) : base(options)
{
}
}
public class Entity
{
[Key]
public …Run Code Online (Sandbox Code Playgroud) 我正在使用工作单元模式,该模式在 webapi 请求上执行完所有内容后调用 dbcontext.SaveChanges。在请求的一部分中,我向 dbcontext 添加了一个新客户。
dbContext.Customers.Add(new Customer());
Run Code Online (Sandbox Code Playgroud)
稍后在请求中(通常在域事件处理程序中),我使用相同的 dbcontext 将客户拉回来。
_dbContext.Customers.FirstOrDefault(x => x.Id == id);
public abstract class Customer
{
public Customer()
{
Id = Guid.NewGuid();
}
}
Run Code Online (Sandbox Code Playgroud)
我已经验证 dbContext.Customers.Local 有我期望的对象,但它似乎没有提取本地对象。这可能是因为 Customer 是一个抽象类,由 DirectCustomer 和 InDirectCustomer 实现吗?
为什么?我可以通过配置更改此行为吗?也许我必须合并本地和数据库结果(有点 hacky )。
更新:
class Program
{
static void Main(string[] args)
{
MyDbContext context = new MyDbContext();
Guid customerGuid = Guid.NewGuid();
context.Customers.Add(new DirectCustomer()
{
Id = customerGuid
});
// This does not work, customerFromLocal1 is null
var customerFromLocal1 = context.Customers.FirstOrDefault(x => x.Id …Run Code Online (Sandbox Code Playgroud)