0
votes

Using OData v4 in .Net, I have two classes and can't seem to get the entity relationship between them to be stored in the DB.

public class Customer
{
   int Id {get;set;}
   ...
}
public class Order
{
    int Id {get;set;}
    public virtual Customer customer {get;set;}
   ...
}

WebApiConfig.cs
    builder.EntitySet<Order>("Orders");
    builder.EntityType<Order>().ContainsRequired(o => o.Customer);
    builder.EntitySet<Customer>("Customers";

And my inline code looks like:
    var cust = new Customer(...);
    var order = new Order(...);
    container.AddToOrders(order);
    container.SetLink(order,"Customer", cust);
    container.SaveChanges();

I don't get any errors, but when I debug the controllers, the customer object in the order object is null. If, in the controller, i reset the customer object in the order object, the data gets stored correctly. So it appears that the entity framework portion is working correctly, just can't get the OData client to serialize the inbound Customer object in the Order object.

Any help on what I am missing (from the client side) would be greatly appreciated.

Thanks.

1
I've seen that and that all appears to work from the server to the client. My problem appears to be from the client to the server, like I need to expand my Add request for the Order object (or something like that). I got the behavior I needed on the server by using the .Include() in the controller. I just seem to be missing a piece on the client that triggers the opposite behavior when adding an object with a contained entity object. Make sense? - Tom Lindley

1 Answers

0
votes

Got this resolved. Went back and reread the tutorial and found what I was missing. A combination of [ForeignKey("")] adornment in the class and proper use of the SetLink method. My mistake was in trying to add the entity and create the link in the same Save action. Once I created the entity, saved it, then did the SetLink(), and save that, I had the relationship in the DB. Once this was done, it was a simple matter of either adding the .Expand() to my query, or using LoadProperty() to get the relationships loaded.