如何在读写上下文之间共享InMemory Db

时间:2017-12-27 01:23:34

标签: c# entity-framework ef-core-2.0

我正在研究一个需要支持read db和write db的项目。我决定相应地创建两个上下文。我有一个Web API来与db进行交互。我有一个端点创建一个用户,另一个端点通过id获取用户。我遇到的问题是开发服务器和本地实例,其中使用了InMemory Db,因为开发速度相当快。问题在于读取上下文没有向我提供我使用写入上下文存储的数据。它认为表是空的。在使用调试器进一步检查后,我能够导航并找到“缺失”数据。我不确定有什么问题。

重现的步骤

以下是我项目中的内容

public class WriteContext : IdentityDbContext<User>
{
  public WriteContext(DbContextOptions<WriteContext> options) : base(options) {}
}

public class ReadContext : IdentityDbContext<User>
{
  public ReadContext(DbContextOptions<ReadContext> options) : base(options) {}
}

public class UserController : Controller
{
  private readonly WriteContext _write;
  private readonly ReadContext _read;

  // constructor injection here

  // attributes...
  public IActionResult Post(UserModel model)
  {
    var user = // map model to User
    _write.Users.Add(user);
    _write.SaveChanges();
    return Ok(user);
  }

  // attributes...
  public IActionResult Get(string userId)
  {
    var user = _read.Users.SingleOrDefault(x => x.Id == userId);
    return Ok(user);
  }
}

public class Startup
{
  public void ConfigureServices(IServiceCollection services)
  {
    // other stuff...

    services.AddDbContext<WriteContext>(options => options.UseInMemoryDatabase("MemDb"));
    services.AddDbContext<ReadContext>(options => options.UseInMemoryDatabase("MemDb"));

    // other stuff
  }

  // other stuff
}

通过写入上下文添加用户,然后尝试通过读取上下文获取用户。

进一步的技术细节

EF Core版本:2.0.1 数据库提供者:InMemory 操作系统:macOS Sierra IDE:Jetbrains Rider 2017.2

Corresponding GitHub Issue

0 个答案:

没有答案