DataServiceContext : Update Navigation Collection Property

早过忘川 提交于 2019-12-12 00:54:04

问题


I'm consuming a Odata WebApi.2.1 Service in a Odata v4 client.

When I attempt to update the entity, and I'm getting following error:

"UpdateRelatedObject method only works when the sourceProperty is not collection"

I have below code in my application.

public class Customer
{
    int CustomerId;
    string CustomerName;
    ICollection<Order> Orders;
}


    public void Save()
    {
        foreach (var item in Customer.Orders)
        {
            Context.UpdateRelatedObject(Customer, "Orders", item);
        }

        Context.UpdateObject(Customer);
        Context.SaveChanges();
    }

Here, "Orders" is a navigation property of class Customer. How can i solve this?


回答1:


Rahul

Basically, there are two rules:

  1. It is not valid to Post to any non-collection valued navigation property.
  2. It is not valid to Put/Patch to any collection-valued navigation property.

The public api UpdateRelatedObject in OData client is designed to update the non-collection property. In its open source, there are codes as:

public void UpdateRelatedObject(object source, string sourceProperty, object target)
{
    ...
    ClientPropertyAnnotation property = parentType.GetProperty(sourceProperty, false);
    if (property.IsKnownType || property.IsEntityCollection)
    {
     throw Error.InvalidOperation(Strings.Context_UpdateRelatedObjectNonCollectionOnly);
    }
    ...
}

So, your error message is thrown in the above throw statement.

Normally, you can do as follows to make it work:

  1. Query the related order, for example: GET ~/Customers(2)/Orders(1)
  2. modify the returned order object
  3. update the modified order to call: UpdateObject

Hope it can help you. Thanks.



来源:https://stackoverflow.com/questions/31516358/dataservicecontext-update-navigation-collection-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!