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

时间:2017-09-05 14:07:22

标签: c# expression filtering dynamic-programming

我正在试图找出一种方法来构建我的数据,以便它可以进行模型绑定。我的问题是我必须创建一个查询过滤器,它可以表示数据中的多个表达式。

例如:

  

x => (x.someProperty == true&& x.someOtherProperty == false)|| x.UserId == 2

     

x => (x.someProperty&& x.anotherProperty)|| (x.userId == 3&& x.userIsActive)

我已经创建了这个代表所有表达式的结构,我的问题是如何才能使它成为它的属性Model Bindable

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作为解决方案,但作为一项要求我不能

有没有办法可以优化这个结构,以便在模型可绑定时它仍然可以表示所有简单表达式?或者是否有一种简单的方法可以应用这种结构,以便它可以与模型绑定器一起使用?

修改 万一有人想知道,我的表达式构建器有一个成员表达式的白名单,它会被过滤掉。动态过滤工作我只是想找到一种自然地绑定这个结构的方法,这样我的Controller就可以接受QueryTreeBranch或者接受一个准确表示相同数据的结构。

public class FilterController
{
     [HttpGet]
     [ReadRoute("")]
     public Entity[]  GetList(QueryTreeBranch<Entity> queryRoot)
     {
         //queryRoot no bind :/
     }
}

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

我正在寻找最接近开箱即用的WebApi / MVC框架的解决方案。优选的一个不要求我将输入调整到另一个结构以生成我的表达

3 个答案:

答案 0 :(得分:6)

乍一看,您可以在DTO上拆分过滤逻辑,其中包含一个独立于实体类型的表达式树,以及一个依赖于类型的Expression<Func<T, bool>>生成器。因此,我们可以避免使DTO变得通用和多态,从而导致困难。

可以注意到,您对IFilterResolver<T>使用了多态(2个实现),因为您想说,过滤树的每个节点都是叶子或分支(这也称为{{3} })。

<强>模型

好的,如果这个特定的实现导致问题,让我们尝试另一个:

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适用于递归模型,请参阅disjoint union)。例如。跟随虚拟视图(将它们放在\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 :(得分:0)

您应该为通用类使用自定义数据绑定器。

使用网络表单和question,查看之前版本中有类似需求的此前Microsoft documentation

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

答案 2 :(得分: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;
    }
}

然后将粘合剂注入您的服务:

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...
}