Jim*_*son 6 c# .net-core ef-core-2.2
关于这个答案,我试图通过设置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 int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我通过将 InMemoryDatabaseRoot 设置为所有上下文中的同一对象来使其工作。
private InMemoryDatabaseRoot _root;
private InMemoryDatabaseRoot Root
{
get
{
if(_root == null)
_root = new InMemoryDatabaseRoot();
return _root;
}
}
[Test]
public void MultipleContextTest()
{
var firstContext = new FirstContext(CreateOptions<FirstContext>());
firstContext.Add(new Entity() {Name = "Test"});
firstContext.SaveChanges();
var secondContext = new SecondContext(CreateOptions<SecondContext>());
Assert.AreEqual(firstContext.Entity.Count(), secondContext.Entity.Count());
}
private DbContextOptions CreateOptions<T>() where T : DbContext
{
return new DbContextOptionsBuilder<T>()
.UseInMemoryDatabase("DB", Root)
.Options;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1900 次 |
| 最近记录: |