简体   繁体   English

用于资源过滤的 Dapper 动态查询

[英]Dapper dynamic query for resource filtering

I am trying to do resource filtering the same way I would be using queryable in EF Core but this time with Dapper.我正在尝试以与在 EF Core 中使用可查询的方式相同的方式进行资源过滤,但这次使用的是 Dapper。 In my case, I wish to get all reports and want to be able to query based on the passed filter parameters.就我而言,我希望获取所有报告并希望能够根据传递的过滤器参数进行查询。 This is so far what I have:到目前为止,这是我所拥有的:

        public async Task<List<IssueReport>> GetAll(int? userId = null, bool? onlyOpenIssues = null, int? issueType = null)
    {
        await using var connection = new SqlConnection(_connectionString);
        var baseQuery = "SELECT * FROM IssueReports";

        //TODO: Add resource filtering logic here

        var result = await connection.QueryAsync<IssueReport>(baseQuery);

        return result.ToList();
    }

What can I do in Dapper to dynamically handle filtering for all those passed parameters as well as handling the case of them being null and not querying them in those cases?我可以在 Dapper 中做什么来动态处理所有传递参数的过滤以及处理它们是 null 的情况并且在这些情况下不查询它们?

What can I do in Dapper to dynamically handle filtering for all those passed parameters as well as handling the case of them being null and not querying them in those cases?我可以在 Dapper 中做什么来动态处理所有传递参数的过滤以及处理它们是 null 的情况并且在这些情况下不查询它们?

You can check my demo:你可以查看我的演示:

Almost the same in efcore, use sql command to execute the query,open database and fill在efcore中几乎一样,使用sql命令执行查询,打开数据库并填写

the result to a list, then close database and return the result.结果到列表中,然后关闭数据库并返回结果。

In this example, when I pass userId=1 to this action, it will search the table where Id=1:在此示例中,当我将 userId=1 传递给此操作时,它将搜索 Id=1 的表:

public async Task<List<IssueReport>> GetAll(int? userId = null)
    {
        var result =new List<IssueReport>();
        var baseQuery = @"SELECT * FROM IssueReport WHERE Id = @Id";
        using (SqlConnection connection = new SqlConnection("***your connection string**"))
        {
            connection.Open();
            result = (List<IssueReport>)connection.Query<IssueReport>(baseQuery,new { Id = userId }); //@Id is defined like this
            connection.Close();
        }
        return result.ToList();
    }

Result:结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM