猿问

内存数据库不保存数据

我有一个简单的 web 应用程序,客户端有 angular,服务器端有 asp.net core web-api。我使用 InMemoryDatabase


services.AddDbContext<ItemsContext>(options => options.UseInMemoryDatabase("ItemsDB"));

存储数据以简化开发。但我遇到了一个问题。我在 web-api 上有一个控制器来响应用户的请求:


[Route("api/[controller]")]

public class ItemsController : Controller

{

    private readonly IApiService apiService;


    public ItemsController(IApiService apiService)//using DI from Startup.cs

    {

       this.apiService = apiService;

    }


    [HttpPost, Route("addItem")]

    public async Task<Response> Add([FromBody]Item item)

    {

        return await apiService.Add(item);

    }


    [HttpDelete("{id}")]

    public async Task<Response> Delete(int id)

    {

        return await apiService.Delete(id);

    }


    [HttpPut]

    public async Task<Response> Put([FromBody]Item item)

    {

         return await apiService.Put(item);

    }

}

以及以下 Startup.cs 配置:


public void ConfigureServices(IServiceCollection services)

{

    services.AddMvc();

    services.AddDbContext<ItemsContext>(options => options.UseInMemoryDatabase("ItemsDB"));

    services.AddSingleton<IUnitOfWork, UnitOfWork>(provider => {

        var context = services.BuildServiceProvider().GetService<ItemsContext>();

        return new UnitOfWork(context);

    });

    services.AddSingleton<IApiService, ApiService>(provider => {

        return new ApiService(services);

    });

}

问题是,当我添加新项目时,一切都很好......但是然后我发布了另一个删除该项目的请求,它可能显示根本没有这样的项目,或者有时它可能会删除它......所以换句话说,数据库存在然后消失,我不确定什么时候。


拉莫斯之舞
浏览 171回答 1
1回答
随时随地看视频慕课网APP
我要回答