How to use Delta from Microsoft ASP.NET Web API OData with Code First\JsonMediaTypeFormatter

后端 未结 2 1674
小蘑菇
小蘑菇 2020-12-31 17:53

What is the issue?

I am trying to enable patching in my ASP.net web api app. I\'m using code first entity framework.

I have the following me

2条回答
  •  不知归路
    2020-12-31 18:45

    Thanks to Youssef for investigating and discovering why things weren't working. Hopefully that can get solved down the line.

    I managed to crack this myself in the end after poring over the oData package source. I chose to implement another MediaTypeFormatter that wraps up the logic as it provides easy access tio HttpContent, but there are other ways to achieve this.

    The key part was figuring out how to interpret the code first model, see the commented line below:

    public override Task ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        var builder = new ODataConventionModelBuilder();
    
        // This line will allow you to interpret all the metadata from your code first model
        builder.EntitySet("EfContext");
    
        var model = builder.GetEdmModel();
        var odataFormatters = ODataMediaTypeFormatters.Create(model);
        var delta = content.ReadAsAsync(type, odataFormatters).Result; 
    
        var tcs = new TaskCompletionSource(); 
        tcs.SetResult(delta); 
        return tcs.Task; 
    }
    
    
    

    Hope this saves someone some trouble!

    提交回复
    热议问题