1
votes

I am using https://www.nuget.org/packages/Microsoft.AspNetCore.OData/7.3.0 to expose OData 4 based Querable API using ASP.NET Core 3.1 API

I have EF Data context with keyless entity(Database view), When I try to expose it with OData Convention based model

   modelBuilder
   .Entity<Student>(eb =>
    {
        eb.HasNoKey();
        eb.ToView("vw_students", "public");
    });

And here is my OData EDM Model mapping with EF Core entity type

var edmBuilder = new ODataConventionModelBuilder();
edmBuilder.EntitySet<Student>("Students");       
return edmBuilder.GetEdmModel();

I get an error on this line edmBuilder.GetEdmModel() The entity set 'Students' is based on type 'ODataCore31.Student' that has no keys defined.

My questions- 1) Are Keyless entity types are natively supported by OData model? 2) Is there any workaround?

1

1 Answers

0
votes

It looks like keyless entities are explicitly unsupported in OData's Edm Model Builder: https://github.com/OData/ModelBuilder/blob/86d26d7346e9359e64e5ec08c31ac7e829cbe788/src/Microsoft.OData.ModelBuilder/ODataModelBuilder.cs#L629

So the answer to your first question is no, for the time being.

For the second question, this may not be possible in your use case, but if your keyless entity corresponds to a view on your database, you could actually just build a normal (not keyless) entity if there's a column or combination of columns on this view that's unique. In one of my models, I created an entity class corresponding to a database view, and then added the [Key] attribute to the property on a column on that view that's guaranteed to be unique per record. Then OData treats this just like any other entity. The only caveat here is that it's read-only.

If, on the other hand, you want to surface a keyless entity to OData because it pulls columns from multiple database tables/views (like you could do with a defining query in classic EF), and you don't want to create a new view in your database, I think you're out of luck.