Skip to content

Minimal APIs: How to Return Single Entity #1567

@cornem

Description

@cornem

I'm unable to find information about how to return a single entity using Minimal APIs and OData. All the samples I have found so far only include collections and functions/operations.

What I have tried:

app.MapGet("/api/customers/{id}", (id, ApplicationDbContext db) =>
{
     IQueryable<TEntity> query = db
         .Customers
         .AsNoTracking()
         .Where(e => e.Id == id);

    return SingleResult.Create(query);
})
    .AddODataQueryEndpointFilter()
    .WithODataModel(EdmModelBuilder.Model)
    .WithODataResult();

Doesn't work, results in an exception that says SingleResult wasn't found in the EDM model.

app.MapGet("/api/customers/{id}", (id, ApplicationDbContext db, ODataQueryOptions<TEntity> queryOptions) =>
{
     IQueryable<TEntity> query = db
         .Customers
         .AsNoTracking()
         .Where(e => e.Id == id);

    return queryOptions.ApplyTo(query).Cast<Customer>().FirstOrDefault();
})
    .WithODataModel(EdmModelBuilder.Model)
    .WithODataResult();

This results in an Entity Framework exception, about not being able to map SelectSome to Customer (makes sense).

What is the correct way to do this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions