本文介绍了多态模型可绑定表达式树解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种结构化数据的方法,以使其具有模型可绑定性。我的问题是我必须创建一个查询过滤器,以表示数据中的多个表达式。

I'm trying to figure out a way to structure my data so that it is model bindable. My Issue is that I have to create a query filter which can represent multiple expressions in data.

例如:

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

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

我创建了这个结构,该结构代表了我的Issue很好的所有表达式我该如何使它成为属性Model可绑定

I've created this structure which represents all of the expressions fine my Issue is how can I make this so it's property 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,但是模型绑定器仅绑定到具体类型。我知道我可以编写自定义模型联编程序,但我更喜欢仅使用一种可以工作的结构。

My left an right members just need to be able to be resolved to an IResolvable, but the model binder only binds to concrete types. I know I can write a custom model binder but I'd prefer to just have a structure that works.

我知道我可以将json作为解决方案进行传递,但作为一项要求,我不能

I know I can pass json as a solutions but as a requirement I can't

有没有一种方法可以优化此结构,使其在可以绑定模型的同时仍可以表示所有简单表达式?还是有一种简单的方法可以应用此结构,使其与模型联编程序一起使用?

Is there a way I can refine this structure so that it can still represent all simple expression while being Model Bindable? or is there an easy way I can apply this structure so that it works with the model binder?

编辑
万一有人想知道,我的表达式生成器将其过滤的成员表达式列入白名单。动态筛选工作只是在寻找一种自然绑定此结构的方法,以便我的Controller可以采用QueryTreeBranch或采用可以精确表示相同数据的结构。

EDITJust in case anyone is wondering, my expression builder has a whitelist of member expressions that it it filters on. The dynamic filtering work I just looking for a way to bind this structure naturally so that my Controller can take in a QueryTreeBranch or take in a structure which accurately represent the same data.

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

当前,IFilterResolver有2种实现,需要根据传递的数据动态选择。

Currently the IFilterResolver has 2 implementations which need to be chosen dynamically based on the data passed

我正在寻找最接近现成的WebApi / MVC框架的解决方案。最好是不需要我使输入适应另一种结构以生成我的表达式的

I'm looking for a solution closest to out of the box WebApi / MVC framework. Preferable one that does NOT require me to adapt the input to another structure in order generate my expression

推荐答案

乍一看,您可以DTO上的分离过滤逻辑,它包含独立于实体类型的表达式树,以及 Expression< Func< T,bool>> 的类型相关的生成器。这样我们就可以避免使DTO成为通用的和多态的,而这会造成困难。

At first glance, you can split filtering logic on DTO, which contains an expression tree independent on entity type, and a type-dependent generator of Expression<Func<T, bool>>. Thus we can avoid making DTO generic and polymorphic, which causes the difficulties.

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

One can notice, that you used polymorphism (2 implementations) for IFilterResolver<T> because you want to say, that every node of the filtering tree is either a leaf or a branch (this is also called disjoint union).

模型

好吧,如果此特定实现引起问题,让我们尝试另一个:

Ok, if this certain implementation causes proplems, let's try another one:

public class QueryTreeNode
{
    public NodeType Type { get; set; }
    public QueryTreeBranch Branch { get; set; }
    public QueryTreeLeaf Leaf { get; set; }
}

public enum NodeType
{
    Branch, Leaf
}

当然,您需要对此模型进行验证。

Of course, you will need validation for such model.

因此,节点是分支还是叶子(我在这里稍微简化了一下叶子):

So the node is either a branch or a leaf (I slightly simplified the leaf here):

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不太容易从代码创建,因此可以使用以下类来生成这些对象:

DTOs above are not so convenient to create from code, so one can use following class to generate those objects:

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 文件夹中)。

There should be no problems with binding such a model (ASP.Net MVC is okay with recursive models, see this question). E.g. following dummy views (place them in \Views\Shared\EditorTemplates folder).

对于分支:

@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 ,例如从字符串:

Finally, you can implement an expression generator taking filtering DTO and a type of T, e.g. from string:

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)));
    }
}

更新:

如评论中所述,最好有一个模型类:

As discussed in comments, it's better to have a single model class:

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

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

...and a single editor template:

@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>

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

Again this way requires a lot of validation.

这篇关于多态模型可绑定表达式树解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 02:01