Search code examples
c#entity-frameworkasp.net-web-apientity-framework-4odata

Deep Inserting data with Asp.Net WebApi + EF + Odata


I'm using Odata v4 WebApi 2.2, Entity Framework 6 and Odata v4 proxy client (WPF) in a project.

Consider following code:

//Model Class
public class Order
{
    public int OrderId {get;set;} //Auto Generated Id
    public string OrderDescription {get;set;}

    Public virtual IEnumerable<OrderLine> OrderLines;
}

//Model Class
public class OrderLine
{
    public int OrderId {get;set;} //Auto Generated Id
    public int OrderLineId {get;set;} //Key of the parent entity
    public string PartDescription  {get;set;}

    Public virtual Order Order;
}


//Odata Proxy Client Code
public void insert()
{
    Order order new Order;
    order.OrderDescription = "Test Desc";

    order.Add( new OrderLine{PartDescription = P100}) //OrderId & OrderLineId is null
    order.Add( new OrderLine{PartDescription = P101})//OrderId & OrderLineId is null
    order.Add( new OrderLine{PartDescription = P101})//OrderId & OrderLineId is null

    //When save changes is called OrderId needs to be set to order lines
    Context.SaveChanges();
}

I need to create Order with Order lines from client and send back to database for save. The problem is The keys are auto generated in database for classes Order & OrderLine.

I need to perform a deep insert and the operation needs to be done in following sequence.

  1. Order needs to be inserted first. Before inserting the Order Lines.
  2. The OrderId of Order Lines needs to be set.
  3. Order lines needs to be inserted.

Does EF or Odata V4 supports deep insert? How can I achieve this?


Solution

  • Deep Insert is not supported now, but you may have a work around, use $ref,

    There is a example in WebAPI side:

    https://github.com/xuzhg/WebApiSample/tree/eb795e26547555666410a79b88e3930d22479798/WebApiODataSample