0

As is the recommended pattern in EF Core these days when you have a many to many join we do something like this:

Fluent API, many-to-many in Entity Framework Core

Having done that I'm faced with the issue as to how I go about exposing that in the OData model.

Since technically the Entity type definition has no key property (as it uses a composite key the OData framework doesn't like me adding the set to the model.

Whats the recommended approach to this problem?

War
  • 8,539
  • 4
  • 46
  • 98

1 Answers1

1

It seems that EF and OData have become somewhat synced up, what would be even better would be if they could literally share model building code.

To that end I found that in the OData model build after calling AddSet I was able to define the key in the same way as I did in EF ...

Builder.EntityType<UserRole>().HasKey(ac => new { ac.UserId, ac.RoleId });

This is somewhat clean, I have not yet tried posting or directly requesting such a type yet, but expanding from either side of the relationship chain seems to work fine.

EDIT: Moredetails on the definition of this in controller ...

The Url needs to contain both key parts ... HTTP GET ~/UserRole(123, 456)

the same with PUTs and DELETEs but POST's don't contain the key they are part of the object in the body.

The method signature must contain both key parts, here's some examples ...

public IActionResult Get([FromODataUri]int keyUserId, [FromODataUri]Guid keyRoleId)
{
    ...
}

public IActionResult Put([FromODataUri]int keyUserId, [FromODataUri]Guid keyRoleId)
{
    ...
}

public IActionResult Post(UserRole entity)
{
    ...
}
War
  • 8,539
  • 4
  • 46
  • 98