Dilshod K
Dilshod K

Reputation: 3032

How to add Context Guid in OData request

I have helper class and each context is creating on that. Each context added on Contexts list:

 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>();
 }

I have action for editing Product name:

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

Also, I have OData service:

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

Here is use case: Let's say we have 'Candy' product in DB. I run EditProduct action and change name to 'COKE'. As you can see I'm not saving context in this action. When I get it from OData, product name is still 'Candy'. It is because context was not saved. I want to be able to use existing contexts in OData. That's why I created GetContext method. Now my OData request is https://localhost:44326/Products. How can I put context Guid in this request and get context from Helper.Contexts list in GetContext method?

Upvotes: 1

Views: 264

Answers (1)

Entony
Entony

Reputation: 26

You can create new route for it:

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

Upvotes: 1

Related Questions