1
votes

I am currently working with WebApi OData on a project and have run into a very frustrating problem. I am using an Entity Framework database-fist model using the EF5 DbContext setup as is the default with Visual Studio 2012 and .NET 4.5. My problem is that if I use the OdataModelConventionBuilder on my entities from Entity Framework to generate my Edm for the OData endpoints, the OData $metadata does not find any of the Key values nor does it properly generate the associations between entities.

I believe that this is because the DbContext generated entities do not have the DataAnnotation attributes on them. If I add the attributes, the keys suddenly work, but this is not a solution since those attributes will be lost if the model is ever regenerated.

Is there a known workaround for this issue?

I am currently having to build my OData Edm by hand using the ODataModelBuilder and it is proving tedious and error-prone.

1

1 Answers

2
votes

You can use the ODataConventionModelBuilder in a partial fashion i.e give it the information that you would have given through the attributes. Assuming you have a 'Customer' type with key property being 'Name' and a 'Customers' entityset, instead of doing something like,

ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
var customers = builder.Entityset<Customer>("Customers");
return builder.GetEdmModel();

you can do something like,

ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
var customers = builder.Entityset<Customer>("Customers");
customers.EntityType.HasKey(c => c.Name); // tell the key explicitly through code
return builder.GetEdmModel();

That should infer the rest of the model.

Also, we have this bug tracking to re-use the EDM model created by Entityframework or some other library. We have it scheduled for the current release. Hopefully, your scenario would be simpler then.