gpt4 book ai didi

c# - 具有相同名称的多个内存数据库

转载 作者:行者123 更新时间:2023-11-30 22:56:43 27 4
gpt4 key购买 nike

关于this answer ,我试图通过将 UseInMemoryDatabase 设置为相同的名称来让多个上下文工作。下面的测试失败,secondContext 为空。

我还需要做什么才能在内存数据库中共享相同内容?

[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; }
}

最佳答案

我通过在所有上下文中将 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;
}

关于c# - 具有相同名称的多个内存数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54193986/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com