多态模型可绑定表达式树解析器

12
我正在尝试找出一种结构化数据的方法,使其可以进行模型绑定。我的问题是我必须创建一个查询过滤器,它可以表示数据中的多个表达式。
例如:
x => (x.someProperty == true && x.someOtherProperty == false) || x.UserId == 2
x => (x.someProperty && x.anotherProperty) || (x.userId == 3 && x.userIsActive)
我已经创建了这个结构来表示所有的表达式,但我的问题是如何使其成为属性模型可绑定的。
public enum FilterCondition
{
    Equals,
}

public enum ExpressionCombine
{
    And = 0,
    Or
}

public interface IFilterResolver<T>
{
    Expression<Func<T, bool>> ResolveExpression();
}

public class QueryTreeNode<T> : IFilterResolver<T>
{
    public string PropertyName { get; set; }
    public FilterCondition FilterCondition { get; set; }
    public string Value { get; set; }
    public bool isNegated { get; set; }

    public Expression<Func<T, bool>> ResolveExpression()
    {
        return this.BuildSimpleFilter();
    }
}

//TODO: rename this class
public class QueryTreeBranch<T> : IFilterResolver<T>
{
    public QueryTreeBranch(IFilterResolver<T> left, IFilterResolver<T> right, ExpressionCombine combinor)
    {
        this.Left = left;
        this.Right = right;
        this.Combinor = combinor;
    }

    public IFilterResolver<T> Left { get; set; }
    public IFilterResolver<T> Right { get; set; }
    public ExpressionCombine Combinor { get; set; }

    public Expression<Func<T, bool>> ResolveExpression()
    {
        var leftExpression = Left.ResolveExpression();
        var rightExpression = Right.ResolveExpression();

        return leftExpression.Combine(rightExpression, Combinor);
    }
}

我的左右成员只需要能够被解析为IResolvable,但模型绑定器只绑定具体类型。我知道我可以编写自定义模型绑定器,但我更喜欢有一个可用的结构。
我知道我可以将json作为解决方案传递,但作为要求,我不能这样做。
有没有办法优化这个结构,使其仍然能够表示所有简单表达式,同时可以进行模型绑定?还是有一种简单的方法可以应用这个结构,使其与模型绑定器配合使用?
编辑:以防万一,我的表达式生成器有一个白名单成员表达式过滤器。动态过滤工作只是在寻找一种自然地绑定此结构的方式,以便我的控制器可以接收QueryTreeBranch或接收准确表示相同数据的结构。
public class FilterController
{
     [HttpGet]
     [ReadRoute("")]
     public Entity[]  GetList(QueryTreeBranch<Entity> queryRoot)
     {
         //queryRoot no bind :/
     }
}

目前IFilterResolver有两个实现,需要根据传递的数据动态选择

我正在寻找最接近WebApi / MVC框架的开箱即用解决方案。最好不需要我将输入调整为另一种结构以生成表达式


你有一个固定的表达式查询过滤器集合可以使用,还是完全动态的呢? - aaronR
2
你能提供一个未能正常工作的示例来说明你想要这个程序实现什么吗? - bruno.almeida
@aaronR 我通常使用成员表达式来将我的访问列入白名单。我稍后会更新问题。 - johnny 5
@Nkosi 最终这将成为一个轻量级的OData,但我允许客户端传递简单的过滤器并且白名单我的访问,因此您可以动态地过滤实体。例如:{ propertyName: "Id", filterCondition: "equals", value: "3" } - johnny 5
@Nkosi 我需要支持简单的二进制表达式和或等。 - johnny 5
显示剩余6条评论
3个回答

6
乍一看,您可以将过滤逻辑拆分为DTO,其中包含独立于实体类型的表达式树和一个类型相关的Expression<Func<T, bool>>生成器。因此,我们可以避免使DTO具有泛型和多态性,这会导致困难。
可以注意到,您对IFilterResolver<T>使用了多态(2个实现),因为您想要表达筛选树的每个节点都是叶子节点或分支节点(这也称为不交并)。 模型 好的,如果这种特定实现引起问题,让我们尝试另一种实现:
public class QueryTreeNode
{
    public NodeType Type { get; set; }
    public QueryTreeBranch Branch { get; set; }
    public QueryTreeLeaf Leaf { get; set; }
}

public enum NodeType
{
    Branch, Leaf
}

当然,对于这样的模型,您需要进行验证。
因此,节点可以是分支或叶子(我在这里稍微简化了叶子)。
public class QueryTreeBranch
{
    public QueryTreeNode Left { get; set; }
    public QueryTreeNode Right { get; set; }
    public ExpressionCombine Combinor { get; set; }
}

public class QueryTreeLeaf
{
    public string PropertyName { get; set; }
    public string Value { get; set; }
}

public enum ExpressionCombine
{
    And = 0, Or
}

以上的DTO(数据传输对象)不太方便从代码中创建,因此可以使用以下类来生成这些对象:

public static class QueryTreeHelper
{
    public static QueryTreeNode Leaf(string property, int value)
    {
        return new QueryTreeNode
        {
            Type = NodeType.Leaf,
            Leaf = new QueryTreeLeaf
            {
                PropertyName = property,
                Value = value.ToString()
            }
        };
    }

    public static QueryTreeNode Branch(QueryTreeNode left, QueryTreeNode right)
    {
        return new QueryTreeNode
        {
            Type = NodeType.Branch,
            Branch = new QueryTreeBranch
            {
                Left = left,
                Right = right
            }
        };
    }
}

查看

绑定这样的模型不应该有问题(ASP.Net MVC可以处理递归模型,参见这个问题)。例如,以下虚拟视图(将它们放在\Views\Shared\EditorTemplates文件夹中)。

对于分支:

@model WebApplication1.Models.QueryTreeBranch

<h4>Branch</h4>
<div style="border-left-style: dotted">
    @{
        <div>@Html.EditorFor(x => x.Left)</div>
        <div>@Html.EditorFor(x => x.Right)</div>
    }
</div>

对于叶子节点:

@model WebApplication1.Models.QueryTreeLeaf

<div>
    @{
        <div>@Html.LabelFor(x => x.PropertyName)</div>
        <div>@Html.EditorFor(x => x.PropertyName)</div>
        <div>@Html.LabelFor(x => x.Value)</div>
        <div>@Html.EditorFor(x => x.Value)</div>
    }
</div>

节点相关:
@model WebApplication1.Models.QueryTreeNode

<div style="margin-left: 15px">
    @{
        if (Model.Type == WebApplication1.Models.NodeType.Branch)
        {
            <div>@Html.EditorFor(x => x.Branch)</div>
        }
        else
        {
            <div>@Html.EditorFor(x => x.Leaf)</div>
        }
    }
</div>

使用示例:

@using (Html.BeginForm("Post"))
{
    <div>@Html.EditorForModel()</div>
}

控制器

最后,您可以实现一个表达式生成器,它接受过滤DTO和T类型,例如从字符串中:

public class SomeRepository
{
    public TEntity[] GetAllEntities<TEntity>()
    {
        // Somehow select a collection of entities of given type TEntity
    }

    public TEntity[] GetEntities<TEntity>(QueryTreeNode queryRoot)
    {
        return GetAllEntities<TEntity>()
            .Where(BuildExpression<TEntity>(queryRoot));
    }

    Expression<Func<TEntity, bool>> BuildExpression<TEntity>(QueryTreeNode queryRoot)
    {
        // Expression building logic
    }
}

然后你从控制器调用它:
using static WebApplication1.Models.QueryTreeHelper;

public class FilterController
{
    [HttpGet]
    [ReadRoute("")]
    public Entity[]  GetList(QueryTreeNode queryRoot, string entityType)
    {
        var type = Assembly.GetExecutingAssembly().GetType(entityType);
        var entities = someRepository.GetType()
            .GetMethod("GetEntities")
            .MakeGenericMethod(type)
            .Invoke(dbContext, queryRoot);
    }

    // A sample tree to test the view
    [HttpGet]
    public ActionResult Sample()
    {
        return View(
            Branch(
                Branch(
                    Leaf("a", 1),
                    Branch(
                        Leaf("d", 4),
                        Leaf("b", 2))),
                Leaf("c", 3)));
    }
}

更新:

如评论所讨论,最好只有一个模型类:

public class QueryTreeNode
{
    // Branch data (should be null for leaf)
    public QueryTreeNode LeftBranch { get; set; }
    public QueryTreeNode RightBranch { get; set; }

    // Leaf data (should be null for branch)
    public string PropertyName { get; set; }
    public string Value { get; set; }
}

...和一个单一的编辑器模板:

@model WebApplication1.Models.QueryTreeNode

<div style="margin-left: 15px">
    @{
        if (Model.PropertyName == null)
        {
            <h4>Branch</h4>
            <div style="border-left-style: dotted">
                <div>@Html.EditorFor(x => x.LeftBranch)</div>
                <div>@Html.EditorFor(x => x.RightBranch)</div>
            </div>
        }
        else
        {
            <div>
                <div>@Html.LabelFor(x => x.PropertyName)</div>
                <div>@Html.EditorFor(x => x.PropertyName)</div>
                <div>@Html.LabelFor(x => x.Value)</div>
                <div>@Html.EditorFor(x => x.Value)</div>
            </div>
        }
    }
</div>

再次,这种方法需要大量验证。


+1 这绝对是有效的,应该可以工作,只是我不喜欢这个 1,你有一个实体定义了 2 个对象,但每次只有 1 个是有效的,现在我必须使用 3 个模型,当可能有一种方法可以用 1 个模型完成时。 - johnny 5
@johnny5 我同意。不幸的是,C#似乎没有一种漂亮的方式来定义不相交的联合 - 这是主要问题。正如我所写的那样,我的实现是为了让模型绑定程序满意而做出的妥协。 - stop-cran
@johnny5 我认为这里可能只需要一个模型对象,可以看一下答案中的更新。 - stop-cran
我本来希望能够以某种神奇的方式找到更简洁的方法来完成这个任务,但看起来这似乎是唯一的方法。谢谢。 - johnny 5

0

你应该为你的泛型类使用自定义数据绑定器。

参考之前使用Web表单的旧版本中有类似需求的问题Microsoft文档

另一个选择是传递类的序列化版本。


问题不在于泛型,而是绑定一个具有两个实现的接口,应该根据数据进行解决。 - johnny 5
第二个实现是什么? - aaronR
这不就是一种实现方式吗?它在两个属性上使用的是相同的方法,只是稍有不同而已。 - aaronR
IFilterResolver 可以是 QueryTreeNode 或 QueryTreeBranch,其类应根据提供的数据进行选择。 - johnny 5

0

我创建了一个基于标准 ComplexTypeModelBinder 的接口绑定器

//Redefine IModelBinder so that when the ModelBinderProvider Casts it to an 
//IModelBinder it uses our new BindModelAsync
public class InterfaceBinder : ComplexTypeModelBinder, IModelBinder
{
    protected TypeResolverOptions _options;
    //protected Dictionary<Type, ModelMetadata> _modelMetadataMap;
    protected IDictionary<ModelMetadata, IModelBinder> _propertyMap;
    protected ModelBinderProviderContext _binderProviderContext;

    protected InterfaceBinder(TypeResolverOptions options, ModelBinderProviderContext binderProviderContext, IDictionary<ModelMetadata, IModelBinder> propertyMap) : base(propertyMap)
    {
        this._options = options;
        //this._modelMetadataMap = modelMetadataMap;
        this._propertyMap = propertyMap;
        this._binderProviderContext = binderProviderContext;
    }

    public InterfaceBinder(TypeResolverOptions options, ModelBinderProviderContext binderProviderContext) :
        this(options, binderProviderContext, new Dictionary<ModelMetadata, IModelBinder>())
    {
    }

    public new Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var propertyNames = bindingContext.HttpContext.Request.Query
            .Select(x => x.Key.Trim());

        var modelName = bindingContext.ModelName;
        if (false == string.IsNullOrEmpty(modelName))
        {
            modelName = modelName + ".";
            propertyNames = propertyNames
                .Where(x => x.StartsWith(modelName, StringComparison.OrdinalIgnoreCase))
                .Select(x => x.Remove(0, modelName.Length));
        }

        //split always returns original object if empty
        propertyNames = propertyNames.Select(p => p.Split('.')[0]);
        var type = ResolveTypeFromCommonProperties(propertyNames, bindingContext.ModelType);

        ModelBindingResult result;
        ModelStateDictionary modelState;
        object model;
        using (var scope = CreateNestedBindingScope(bindingContext, type))
        {
             base.BindModelAsync(bindingContext);
            result = bindingContext.Result;
            modelState = bindingContext.ModelState;
            model = bindingContext.Model;
        }

        bindingContext.ModelState = modelState;
        bindingContext.Result = result;
        bindingContext.Model = model;

        return Task.FromResult(0);
    }

    protected override object CreateModel(ModelBindingContext bindingContext)
    {
        return Activator.CreateInstance(bindingContext.ModelType);
    }

    protected NestedScope CreateNestedBindingScope(ModelBindingContext bindingContext, Type type)
    {
        var modelMetadata = this._binderProviderContext.MetadataProvider.GetMetadataForType(type);

        //TODO: don't create this everytime this should be cached
        this._propertyMap.Clear();
        for (var i = 0; i < modelMetadata.Properties.Count; i++)
        {
            var property = modelMetadata.Properties[i];
            var binder = this._binderProviderContext.CreateBinder(property);
            this._propertyMap.Add(property, binder);
        }

        return bindingContext.EnterNestedScope(modelMetadata, bindingContext.ModelName, bindingContext.ModelName, null);
    }

    protected Type ResolveTypeFromCommonProperties(IEnumerable<string> propertyNames, Type interfaceType)
    {
        var types = this.ConcreteTypesFromInterface(interfaceType);

        //Find the type with the most matching properties, with the least unassigned properties
        var expectedType = types.OrderByDescending(x => x.GetProperties().Select(p => p.Name).Intersect(propertyNames).Count())
            .ThenBy(x => x.GetProperties().Length).FirstOrDefault();

        expectedType = interfaceType.CopyGenericParameters(expectedType);

        if (null == expectedType)
        {
            throw new Exception("No suitable type found for models");
        }

        return expectedType;
    }

    public List<Type> ConcreteTypesFromInterface(Type interfaceType)
    {
        var interfaceTypeInfo = interfaceType.GetTypeInfo();
        if (interfaceTypeInfo.IsGenericType && (false == interfaceTypeInfo.IsGenericTypeDefinition))
        {
            interfaceType = interfaceTypeInfo.GetGenericTypeDefinition();
        }

        this._options.TypeResolverMap.TryGetValue(interfaceType, out var types);
        return types ?? new List<Type>();
    }
}

然后您需要一个模型绑定提供程序:

public class InterfaceBinderProvider : IModelBinderProvider
{
    TypeResolverOptions _options;

    public InterfaceBinderProvider(TypeResolverOptions options)
    {
        this._options = options;
    }
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (!context.Metadata.IsCollectionType &&
            (context.Metadata.ModelType.GetTypeInfo().IsInterface ||
             context.Metadata.ModelType.GetTypeInfo().IsAbstract) &&
            (context.BindingInfo.BindingSource == null ||
            !context.BindingInfo.BindingSource
            .CanAcceptDataFrom(BindingSource.Services)))
        {
            return new InterfaceBinder(this._options, context);
        }

        return null;
    }
}

然后将binder注入到您的服务中:

var interfaceBinderOptions = new TypeResolverOptions();

interfaceBinderOptions.TypeResolverMap.Add(typeof(IFilterResolver<>), 
    new List<Type> { typeof(QueryTreeNode<>), typeof(QueryTreeBranch<>) });
var interfaceProvider = new InterfaceBinderProvider(interfaceBinderOptions);

services.AddSingleton(typeof(TypeResolverOptions), interfaceBinderOptions);

services.AddMvc(config => {
    config.ModelBinderProviders.Insert(0, interfaceProvider);
});

然后你可以按如下设置控制器:

public MessageDTO Get(IFilterResolver<Message> foo)
{
    //now you can resolve expression etc...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接