AutoMapper / AutoMapper.Extensions.OData

Creates LINQ expressions from ODataQueryOptions and executes the query.
MIT License
140 stars 38 forks source link

GetQuery fails on DataMemberAttrubute-marked field with $orderby #174

Open Galgvithr opened 1 year ago

Galgvithr commented 1 year ago

Hello! I've encountered a problem using AutoMapper.AspNetCore.OData.EFCore extension. $orderby call seems to ignore DataMemberAttribute's name of the property.

Source/destination types

// EF model
 [Table("models")]
public class MyEntityModel
{
[Column("id")]
public int Id { get; set; }

[Column("name")]
public string? Name { get; set; }
}

// view model
[DataContract]
public class MyDtoModel
{
    [DataMember(Name = "id")]
    public int Id { get; set; }

    [DataMember(Name = "my_name")] 
    public string? Name { get; set; }
}

Mapping configuration

// default mapping between EF model and view model
CreateMap<MyEntityModel, MyDtoModel>();

Versions:

AutoMapper 12.0.1 AutoMapper.AspNetCore.OData.EFCore 4.0.0 Microsoft.AspNetCore.OData 8.0.12 Microsoft.EntityFrameworkCore.InMemory 7.0.2 OR Npgsql.EntityFrameworkCore.PostgreSQL 6.0.7 (EF version seems to be irrelevant for this bug)

Steps to reproduce

  1. Create ASP.NET project configured for default OData usage with following controller method:

    [HttpGet]
    public async Task<IActionResult> Get(ODataQueryOptions<MyDtoModel> odata)
    {
    var query = _context.Entities;
    
    return Ok(query.GetQuery(_mapper, odata));
    }
  2. Use in-memory EF context, populate DbSet with one or more instances of MyEntityModel

    public TestContext(DbContextOptions<TestContext> op): base(op)
    {
        CreateRecords();
    }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyEntityModel>().HasKey(p => p.Id);
    }
    
    public DbSet<MyEntityModel> Entities { get; set; }
    
    private void CreateRecords()
    {
        {
            if (Entities?.Any() ?? false)
            {
                return;  
            }
            Entities.AddRange(
                new MyEntityModel()
                {
                    Id = 1,
                    Name = "1"
                });
    
            SaveChanges();
        }
    }
  3. Send OData-request with query: ?$orderby=my_name+asc

Expected behavior

Request finishes: rows are extracted from DB as mapped DTOs. Collection of objects serialises, just like the similar query: ?$orderby=id+asc Which results in this response body:

[
    {
        "id": 1,
        "name": "1"
    }
]

Actual behavior

Request results in status code 500 Internal Server Error with argument exception:

System.ArgumentException: Member my_name, does not exists in type ODataEfCore_DataMember_Test.Controllers.MyDtoModel. at LogicBuilder.Expressions.Utils.TypeExtensions.GetMemberInfo(Type parentType, String memberName) at LogicBuilder.Expressions.Utils.TypeExtensions.GetMemberInfoFromFullName(Type type, String propertyFullName) at AutoMapper.AspNet.OData.LinqExtensions.GetOrderByCall(Expression expression, String memberFullName, String methodName, String selectorParameterName) at AutoMapper.AspNet.OData.LinqExtensions.g__GetMethodCall|10_0(<>c__DisplayClass10_0& ) at AutoMapper.AspNet.OData.LinqExtensions.GetOrderByCall(Expression expression, OrderByClause orderByClause, ODataQueryContext context) at AutoMapper.AspNet.OData.LinqExtensions.GetQueryableMethod(Expression expression, ODataQueryContext context, OrderByClause orderByClause, Type type, Nullable1 skip, Nullable1 top) at AutoMapper.AspNet.OData.LinqExtensions.GetOrderByMethod[T](Expression expression, ODataQueryOptions1 options, ODataSettings oDataSettings) at AutoMapper.AspNet.OData.LinqExtensions.GetQueryableExpression[T](ODataQueryOptions1 options, ODataSettings oDataSettings)

$filter seems to not be affected by this bug. I've tried the query: $filter=my_name eq '1' So, i presume, $orderby should also work with DataMemberAttrubite.

BlaiseD commented 1 year ago

The root filter uses ApplyTo from Microsoft.AspNetCore.OData.Query. You'll find the nested filter also ignores the DataMemberAttribute - it isn't implemented at all. Ok to create PR.