-1

我正在做一个Asp.net core 5项目。我创建了一个action filter适用于HttPost特别是 的操作create,此过滤器将检查数据库中是否已存在具有从model.

我如何使用它: 过滤器应该接收entity要签入的,以及要签入的属性名称,以及在存在记录的情况下显示entity错误消息。

过滤器定义: 我觉得有点复杂

public class RecordShouldNotExistFilterAttribute:TypeFilterAttribute
{

    public RecordShouldNotExistFilterAttribute( Type entityType, string errorMessage= "Existe déjà", params string[] propertiesToBeChecked) : base( typeof(RecordShouldNotExistFilter<>).MakeGenericType(entityType))
    {
        Arguments = new object[] {errorMessage , propertiesToBeChecked};
    }

}

public class RecordShouldNotExistFilter<TEntity>:IActionFilter where  TEntity : class
{

    private readonly AppDbContext _dbContext;
    public           string[]     PropertiesToBeChecked { get; set; }
    public           string       ErrorMessage          { get; set; }

    public RecordShouldNotExistFilter( AppDbContext dbContext ,string errorMessage,params string[] propertiesToBeChecked)
    {
        _dbContext            = dbContext;
        PropertiesToBeChecked = propertiesToBeChecked;
        ErrorMessage          = errorMessage;
    }

    public void OnActionExecuting( ActionExecutingContext context )
    {

        Expression queryExpression = null;

        context.ActionArguments.TryGetValue( "model" , out var model );

        var param = Expression.Parameter(typeof(TEntity));

        foreach ( var property in PropertiesToBeChecked )
        {
            var propValue = model?.GetType().GetProperty( property )?.GetValue( model );

            var equalExpression = Expression.Equal( left : Expression.Property( param , property) , right : Expression.Constant( propValue ) );

            queryExpression = queryExpression == null ? equalExpression : Expression.And( queryExpression , equalExpression );
        }

        var condition = Expression.Lambda<Func<TEntity , bool>>( queryExpression , param );

        var result = _dbContext.Set<TEntity>().Where( condition );

        if ( result.Any() )
        {
            context.Result = RedirectToActionResult( action : "ExistError" , controller : "/Exception" ,errorModel: new ErrorModel()
                                                                                                         {
                                                                                                             Title       = "Existe déjà" ,
                                                                                                             Description = $"{ErrorMessage}" ,
                                                                                                             ReturnUrl   = "/Dashboard"
                                                                                                         } );
        }


    }

    public void OnActionExecuted( ActionExecutedContext   context )
    {
        
    }

    #region Private methods

    private static RedirectToActionResult RedirectToActionResult(string action, string controller, ErrorModel errorModel)
    {
        return new RedirectToActionResult(action, controller, errorModel);
    }

    #endregion

}

与动作一起使用的示例:

[RecordShouldNotExistFilter(entityType: typeof(PedagogicalSequence), errorMessage: "A record with the same ID already exists",propertiesToBeChecked: nameof(Branche.Id))]
    public IActionResult Create(Branche model)
    {
    //Some logic here
    }

问题:

问题出在Action我收到此错误 InvalidOperationException:未为类型“System.Int32”和“System.String”定义二元运算符 Equal。System.Linq.Expressions.Expression.GetEqualityComparisonOperator(ExpressionType binaryType,字符串 opName,表达式左,表达式右,bool liftToNull)

错误画面: 在此处输入图像描述

请帮助解决这个问题?

4

1 回答 1

0

就我而言:

[RecordShouldNotExistFilter(entityType: typeof(PedagogicalSequence), errorMessage: "A record with the same ID already exists",propertiesToBeChecked: nameof(Branche.Id))]

我发送了错误的实体。

我改变了它,一切都很好

于 2021-04-27T04:40:28.880 回答