0

I am new to Odata as well as EntityFramework, And I am trying to use OData with DTOs. My Entity Model have been defined something like

public Orders
{
    public String OrderId{get; set;}
    public List<Item>? Items{get;set;}
}

public Item
{
    public String ItemId{get; set;}
    public String ItemType{get; set;}
}

And My query is something like

_db.Orders.Select(o => new OrdersDTO
{
    OrderId = o.OrderId,
    // This works if I dont register Item DTO in my Odata EDM model 
    // Even if I comment this I still get the same error
    Items = o.Items.Select(i => new Item
    {
        ItemId = i.ItemId, 
        ItemType = i.ItemType
    }).ToList()
}

Now even when I have not mentioned the Item in my Select of the Query it is giving me an error that Error creating query string:

Error creating query string: The LINQ expression '$it => new SelectAll<Item>{ 
    Model = __TypedProperty_2, 
    Instance = $it, 
    UseInstanceForProperties = True 
}

I would ideally like Odata to dynamically create a SQL query that fetches only the data required. As it does in case of direct Entities.

I tried https://github.com/dotnet/efcore/issues/27460 one of the solutions saying to set null propagation as false, but I am still facing the same error.

I feel there is something I am not understanding fundamentally the way DTOs need to be defined.

EDIT : I found out that when I remove the Item Object from my Odata EDM model, the query works as expected. However removing that means I can no longer use the '$expand' option in Odata Query. Furthermore, even if I dont keep the explicit Select for the list, it still gives me the same error.

_db.Orders.Select(o => new OrdersDTO
{
    OrderId = o.OrderId
    // Even when I have not mentioned the Item mapping it still gives 
    //me an error
})
1
  • 1
    Everything relies on how EF translates query. Its ability improved year by year, but not so much. Try without .ToList() Commented Jan 15 at 6:57

1 Answer 1

0

Using EF mapping techniques like

It's not necessary for your EF entities to be exactly like your underlying database tables. So you can ditch the DTOs and maintain the mapping layer in the EF model configuration, enabling OData to generate the queries directly against the model.

Sign up to request clarification or add additional context in comments.

1 Comment

But would it not be possible to do this with DTO? I am facing this issue only when my DTO model has a list. But as you said if I use the EF Entity Directly with Odata it does not give me the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.