Ankit
Ankit

Reputation: 2518

How to utilize existing keys defined in OnModelCreating (Fluent Api EF) to work with ODataModelBuilder in OData v4?

I have to implement an OData API in a Web API project.

There is very good article about doing it here(entity relations) and here(composite key). But all the sources are using data annotations to set keys.

In my project all the constraints on entities have been defined using Fluent Api in context class.

public class DataContext : DbContext
{
    public DataContext()
    {
    }
    public virtual DbSet<Person> Person { get; set; }
    public virtual DbSet<Car> Car { get; set; }
     ...
     ...

    protected override void OnModelCreating(DbModelBuilder mb)
    {
        ...
         mb.Entity<Person>().HasKey(jq => new { p.Key1, p.Key2 });
        ...
    }

}

To use OData i have to register the individual entities using in WebApi.config.

ODataModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Person>("Person"); 

How do i go about registering constraints for it in WebApi.config?

Is there any solution without declaring keys(using data annotations)?


The entity design is already being used by lots of Web Api controllers. So, i wish to reuse the existing model without having to redefine the constraints for only one OData Controller.

Upvotes: 4

Views: 684

Answers (1)

TomDoesCode
TomDoesCode

Reputation: 3681

I'm not sure how or if you can reuse the keys in the context class but you can set them on the entity set that you are creating in WebApi.config by using the object that is returned from the EntitySet method like this:

var personEntitySet = pobjBuilder.EntitySet<Person>("Person");
personEntitySet.EntityType.HasKey<int>(x => x.Key1);
personEntitySet.EntityType.HasKey<int>(x => x.Key2);

Upvotes: 2

Related Questions