问题
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:
- It is not valid to Post to any non-collection valued navigation property.
- 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:
- Query the related order, for example: GET ~/Customers(2)/Orders(1)
- modify the returned order object
- update the modified order to call: UpdateObject
Hope it can help you. Thanks.
来源:https://stackoverflow.com/questions/31516358/dataservicecontext-update-navigation-collection-property