enisn / AutoFilterer

AutoFilterer is a mini filtering framework library for dotnet. The main purpose of the library is to generate LINQ expressions for Entities over DTOs automatically. The first aim is to be compatible with Open API 3.0 Specifications
MIT License
458 stars 37 forks source link

bug? not execute Custom Expression #65

Open neozhu opened 1 year ago

neozhu commented 1 year ago

there is my code: image

image

enisn commented 1 year ago

As I understand you say the breakpoint never be hit inside your custom attribute. Right?

Let me check it

neozhu commented 1 year ago

As I understand you say the breakpoint never be hit inside your custom attribute. Right?

Let me check it

yes, right

enisn commented 1 year ago

It should be working and tests are passed. But can you try to pass it as a parameter of [CompareTo] attribute like the following:

[CompareTo(typeof([SearchProductsWithListViewAttribute), "ListView")]
public ProductListView ListView { get; set; }
enisn commented 1 year ago

Here my Test class:

public class CustomAttributesTests
{
    public enum MyEnum
    {
        ValueA, ValueB, ValueC, ValueD, ValueE,
    }

    public class MyEnumFilterAttribute : FilteringOptionsBaseAttribute
    {
        public static bool IsExecuted { get; set; }
        public override Expression BuildExpression(Expression expressionBody, PropertyInfo targetProperty, PropertyInfo filterProperty, object value)
        {
            IsExecuted = true;

            return expressionBody;
        }
    }

    public class FooFilter : FilterBase
    {
        [MyEnumFilter]
        public MyEnum Value { get; set; }
    }

    public class FooEntity
    {
        public MyEnum Value { get; set; }
    }

    [Theory, AutoMoqData(count: 64)]
    public void CustomMethodShouldBeCalled(List<FooEntity> entities)
    {
        var filter = new FooFilter();
        MyEnumFilterAttribute.IsExecuted = false;

        var query = entities.AsQueryable().ApplyFilter(filter);

        MyEnumFilterAttribute.IsExecuted.Should().BeTrue();
    }
}

As I get it, you don't have the property with the same name in your entity, so FilterBase ignores that property since there no matched property in the entity. This is a tough situation, maybe there might be some changes required in the AutoFilterer. The library shouldn't assume that there is always matching properties in the entity.

neozhu commented 1 year ago

thank you for your information. Yes, It's working.

[CompareTo(typeof(SearchProductsWithListView), "Name")] public ProductListView ListView { get; set; } = ProductListView.All;

The property name “Name” must be the same as the property name of the Entity Object.

Now I have a requirement that when the value of ProductListView is "My Products", I need to query records where CreatedBy equals the current user ID. I would like to pass the current user ID as a parameter. If I declare the property using [CompareTo(typeof(SearchProductsWithListView), "Name")], how can I pass the parameter?

image
neozhu commented 1 year ago

I want to use Dependency Injection with SearchProductsWithListView to pass the current user. but not working

services.AddScoped<SearchProductsWithListView>();

public enum ProductListView
{
    [Description("All")]
    All,
    [Description("My Products")]
    My,
    [Description("Created Toady")]
    CreatedToday,
    [Description("Created within the last 30 days")]
    Created30Days
}

public class SearchProductsWithListView : FilteringOptionsBaseAttribute
{
    private readonly ICurrentUserService _currentUserService;

    public SearchProductsWithListView(ICurrentUserService currentUserService)
    {
        _currentUserService = currentUserService;
    }
    public override Expression BuildExpression(Expression expressionBody, PropertyInfo targetProperty, PropertyInfo filterProperty, object value)
    {
        var today = DateTime.Now.Date;
        var start = Convert.ToDateTime(today.ToString("yyyy-MM-dd", CultureInfo.CurrentCulture) + " 00:00:00", CultureInfo.CurrentCulture);
        var end = Convert.ToDateTime(today.ToString("yyyy-MM-dd", CultureInfo.CurrentCulture) + " 23:59:59", CultureInfo.CurrentCulture);
        var end30 = Convert.ToDateTime(today.AddDays(30).ToString("yyyy-MM-dd", CultureInfo.CurrentCulture) + " 23:59:59", CultureInfo.CurrentCulture);
        var userId = _currentUserService.UserId;
        var listview = (ProductListView)value;
        return listview switch
        {
            ProductListView.All => expressionBody,
           ProductListView.My=>  Expression.Equal(Expression.Property(expressionBody, "CreatedBy"),  Expression.Constant(userId)),
            ProductListView.CreatedToday => Expression.GreaterThanOrEqual(Expression.Property(expressionBody, "Created"),
                                                                          Expression.Constant(start, typeof(DateTime?)))
                                            .Combine(Expression.LessThanOrEqual(Expression.Property(expressionBody, "Created"),
                                                     Expression.Constant(end, typeof(DateTime?))),
                                                     CombineType.And),
            ProductListView.Created30Days => Expression.GreaterThanOrEqual(Expression.Property(expressionBody, "Created"),
                                             Expression.Constant(start, typeof(DateTime?)))
                                             .Combine(Expression.LessThanOrEqual(Expression.Property(expressionBody, "Created"),
                                                     Expression.Constant(end30, typeof(DateTime?))),
                                                     CombineType.And),
            _ => expressionBody
        };
    }
}
enisn commented 1 year ago

I want to use Dependency Injection with SearchProductsWithListView to pass the current user. but not working

Unfortunately, it's just a C# attribute and it doesn't support dependency injection. I have a plan for dependency injection compatibility ( #52 ) But I see there is a performance gap between regular one that uses DI.

This kind of dynamic parameters are not the main focus of AutoFilterer at the moment. But after #52 is implemented, it'll be quite possible to filter.

neozhu commented 1 year ago

thank you for your information, You know IActionFilter support DI inject IHttpContextAccessor

enisn commented 1 year ago

Yeah, you're right, but AutoFilterer is an independent library and it doesn't have any reference to AspNetCore. Maybe an alternative attribute can be developed which extends IActionFilter