【问题标题】:Polymorphic Model Bindable Expression Trees Resolver多态模型可绑定表达式树解析器
【发布时间】:2018-02-13 20:55: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 作为解决方案传递,但作为要求我不能

有没有一种方法可以改进这个结构,使其在模型可绑定的同时仍然可以表示所有简单的表达式?还是有一种简单的方法可以应用此结构以便它与模型绑定器一起使用?

编辑 万一有人想知道,我的表达式构建器有一个它过滤的成员表达式白名单。动态过滤工作我只是在寻找一种自然绑定此结构的方法,以便我的 Controller 可以接收 QueryTreeBranch 或接收准确表示相同数据的结构。

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

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

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

【问题讨论】:

  • 你有一套固定的表达式,查询过滤器,可以使用还是完全动态的?
  • 你能提供一个不可行的例子来说明你想要这样做吗?
  • @aaronR 我正在使用成员表达式将我的访问权限列入白名单,我将在一秒钟内更新问题
  • @Nkosi 最终这将是一个轻量级的 OData,但我允许客户端传入简单的过滤器并将我的访问列入白名单,因此您可以动态过滤实体。 IE { propertyName: "Id", filterCondition: "equals", value: "3" }
  • @Nkosi 我需要支持简单的二进制表达式等

标签: c# expression filtering dynamic-programming


【解决方案1】:

乍一看,你可以在DTO上拆分过滤逻辑,它包含一个独立于实体类型的表达式树,以及一个依赖于类型的生成器Expression&lt;Func&lt;T, bool&gt;&gt;。这样我们就可以避免让 DTO 泛型化和多态化而带来的困难。

可以注意到,您对IFilterResolver&lt;T&gt; 使用了多态性(2 个实现),因为您想说,过滤树的每个节点都是叶子或分支(这也称为disjoint union)。

型号

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

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 可以使用递归模型,请参阅this question)。例如。跟随虚拟视图(将它们放在\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)));
    }
}

更新:

正如 cmets 中所讨论的,最好有一个模型类:

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 做到这一点时
  • @johnny5 我同意。不幸的是,C# 似乎没有很好的方法来定义不相交的联合——这是这里的主要问题。正如我所写,我的实现是为了让模型绑定器满意而做出的权衡。
  • @johnny5 我认为这里可能只有 1 个模型对象,请参阅答案中的更新。
  • 我希望能神奇地找到一种更清洁的方法来做到这一点,但这看起来是唯一的方法'谢谢
【解决方案2】:

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

请参阅以前的question,它在使用网络表单和Microsoft documentation 的以前版本中具有类似的需求。

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

【讨论】:

  • 问题不在于泛型,而是将接口与 2 个应根据数据解决的实现绑定在一起
  • 第二个实现是什么?
  • 这不是一种实现方式相同而是用于两个属性的实现方式吗?
  • IFilterResolver 可以是 QueryTreeNode 或 QueryTreeBranch,应根据提供的数据选择其类
【解决方案3】:

我创建了一个使用标准 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...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    相关资源
    最近更新 更多