如何在 OData 请求中添加 Context Guid

How to add Context Guid in OData request

我有助手 class,每个上下文都在其上创建。添加到上下文列表中的每个上下文:

 public static class Helper
 {
    public const string CONNECTION_STRING = @"Server=(localdb)\MSSQLLocalDB;Database=MyApp;Trusted_Connection=True;";
    public static MainContext CreateContext()
    {
        DbContextOptionsBuilder<MainContext> optionsBuilder = new DbContextOptionsBuilder<MainContext>().UseSqlServer(CONNECTION_STRING);
        var context = new MainContext(optionsBuilder.Options) { ContextId = Guid.NewGuid() };
        Contexts.Add(context);
        return context;
    }
    public static List<MainContext> Contexts { get; set; } = new List<MainContext>();
 }

我有编辑 Product 姓名的操作:

    public ViewResult EditProduct(string name, string newName)
    {
        var products = Context.GetEntities<Product>().Where(a => a.Name == name);
        foreach (var product in products)
        {
            product.Name = newName;
        }
        return View(products);
    }

此外,我有 OData 服务:

 public IHttpActionResult Get(ODataQueryOptions<Product> queryOptions, CancellationToken cancellationToken)
 {
        Context = GetContext();
        if (Context == null)
        {
            Context = Helper.CreateContext();
        }
        var products = Context.GetEntities<Product>();
        return Ok(products);
 }

这是用例: 假设我们在数据库中有 'Candy' 个产品。我 运行 EditProduct 操作并将名称更改为 'COKE'。如您所见,我没有在此操作中保存上下文。当我从 OData 获取它时,产品名称仍然是 'Candy'。这是因为没有保存上下文。我希望能够在 OData 中使用现有上下文。这就是我创建 GetContext 方法的原因。现在我的 OData 请求是 https://localhost:44326/Products。如何将上下文 Guid 放入此请求并从 Helper.Contexts 列表中的 GetContext 方法中获取上下文?

您可以为其创建新路线:

public IHttpActionResult GetProductsFromContext(Guid contextId)
    {
        var context=Helper.Contexts.FirstOrDefault(c=>c.Id==contextId);
        if(context==null) throw new Exception($"Context with {contextId} was not found");
        var products=context.GetEntities<Product>();
        return OK(products);
    }