.NET Web API OData and Entity Framework Database First: No Key defined

.NET Web API OData and Entity Framework Database First: No Key defined

When using EF database first, I came across an error:

No Key defined…

Turns out the generated classes are not decorated with the [Key] attribute. You can manually add them but once you generate your model(s) again, it’s all gone.
There are workarounds floating across the internet to edit the T4 template(s) that generate these models, but every developer has to do that, plus I didn’t want to fiddle around with those files.

Another way is to map your key(s) in the WebApiConfig class using the ODataModelBuilder.

config.MapHttpAttributeRoutes(); //Needs to happen first
ODataModelBuilder builder = new ODataConventionModelBuilder();

var _dbobj = builder.EntitySet("DBObjects");
_dbobj.EntityType.HasKey(k => k.Id);  

// Multiple key fields: 

var _dbobj = builder.EntitySet("DBObjects");
_dbobj.EntityType.HasKey(k => k.Id1);  
_dbobj.EntityType.HasKey(k => k.Id1);

    routeName: "ODataRoute",
    routePrefix: "api",
    model: builder.GetEdmModel());

You can also add relationships, although I found that mapping those isn’t needed. OData seems to find those relations correctly.

_dbobj.HasManyBinding(m => m.prop1, _dbobj2);
_dbobj.HasManyBinding(m => m.prop3, _dbobj3);

// Or a one to many
_lineItems.HasRequiredBinding(b => b.Order, orders);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.