aweis
aweis

Reputation: 5616

net core odata put and patch nested data structures

I have been using odata in a .net core 2.x web api, and so fare it has worked great, but now I am starting to implement the PUT/PATCH endpoints and I start running into issues with nested structures. In a simple order/item setup as illustrated below I need to manually handle the removal and addition of items to an order if they have changed. I cannot get odata to track nested changes as well.

public class Item
{
    [Key]
    public int Id { get; set; }
    public int OrderId { get; set; }
    public Order Order { get; set; }
}

public class Order
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<Item> Items { get; set; }
}

And my service that updates the order:

public void Update(Order order)
{
    using (var trans = DbContext.Database.BeginTransaction())
    {
        try
        {
            var existingItems = DbContext.Items.Where(t => t.OrderId == order.Id);
            var deleteItems = existingItems.Where(t => order.Items.Count() == 0 || !order.Items.Any(c => c.OrderId == t.OrderId));
            var addItems = order.Items.Where(t => !existingItems.Any(c => c.OrderId == t.OrderId));
            addItems.ToList().ForEach(a => a.OrderId = order.Id);

            DbContext.RemoveRange(deleteItems);
            DbContext.AddRange(addItems);

            DbContext.SaveChanges();

            DbContext.Entry(order).State = EntityState.Modified;
            DbContext.SaveChanges();

            trans.Commit();
        }
        catch (Exception ex)
        {
            trans.Rollback();
            throw ex;
        }
    }
}

Compared to how everything else in Odata works this is a lot of work, and only gets much more complex with deeper nested objects.

Am I doing something wrong, I cannot find much resources on this issue?

Upvotes: 3

Views: 1079

Answers (1)

Joshit
Joshit

Reputation: 1335

It seems like this is currently not supported. I´ve spent some time on investigating this but the only helpful resource is this: http://odata.github.io/WebApi/#03-02-built-in-routing-conventions

That means to me, that we need to write multiple patch-operations in the prinicipal controller for related entities. There are many github-issues on that - but I don´t find any helpful information there.

I´ve asked a question regarding this issue here and one of the contributors confirmed that..

Upvotes: 1

Related Questions