【问题标题】:How to map/join two tables and filter by parameters using dapper如何使用 dapper 映射/连接两个表并按参数过滤
【发布时间】:2020-09-07 12:02:20
【问题描述】:

我想连接两个相互关联的表, 在客户表中,有删除和批准两列。获取已批准且未删除的客户,然后使用 CustId (Both Tables has CustId) 将客户与贷款表匹配并按提供的参数过滤

  • 已删除=0
  • 已批准=1

传递的参数是(并且它们可以是可选的)用户只能传递一个或两个或超过2个 利率 贷款日期 最后付款日期

        public async Task<IEnumerable<Loan>> ManageGettingAll(string InterestRate, string LoanTrfDate, string LastPaymentDate)
        {
            IEnumerable<Loan> loans = null;

            //var sql = "Select * from MonthlyInterest where LoanAccountNo=@Id AND Deleted=@Deleted AND CAST(TranDate AS DATE) BETWEEN @StartDate AND @EndDate";
            try{

                using (var conn = new SqlConnection(connectionstring))
                {
                    await conn.OpenAsync();

                    var parameters = new 
                    { 
                        InterestRate = InterestRate, 
                        LoanTrfDate = LoanTrfDate, 
                        LastPaymentDate = LastPaymentDate
                    };
                   
                string sql = "Select l.*, c.FirstName_CompanyName from dbo.Loan l left join Customer where and l.Deleted = 0 and and l.Approved = 1 c on  l.CustId=c.CustId Where InterestRate=@InterestRate AND CAST(LoanTrfDate AS DATE)=@LoanTrfDate AND CAST(LastPaymentDate AS DATE)=@LastPaymentDate";
                 
                    loans = await conn.QueryAsync<Loan>(sql, parameters);
                }
            }
            catch (Exception ex)
            {

                throw;
            }


            return loans;
        }

【问题讨论】:

  • 要清楚,您的问题是如何仅在指定值的情况下按参数过滤?并忽略它们为空的参数?
  • 至少要传递一个参数
  • 您可以使用 DynamicParameters 对象。您可以检查传递的字符串是否不为空,然后仅将其添加到 DynamicParameters 对象。在 SQL 端,您可以使用 ISNULL(@InterestRate ,InterestRate) 或 Coalease 函数。

标签: c# sql sql-server asp.net-core dapper


【解决方案1】:

仅当参数不为空时才按参数进行过滤,您可以使用下面的 SQL。

Select l.*, c.FirstName_CompanyName 
from dbo.Loan l 
left join Customer c on l.CustId=c.CustId 
where l.Deleted = 0 and l.Approved = 1
and (@InterestRate is null or InterestRate=@InterestRate) 
AND (@LastPaymentDate is null or (CAST(LoanTrfDate AS DATE)=@LoanTrfDate AND CAST(LastPaymentDate AS DATE)=@LastPaymentDate))

要检查是否设置了至少一个参数,您可以添加此 if 语句。

if(string.IsNullOrWhiteSpace(LoanTrfDate) && string.IsNullOrWhiteSpace(LastPaymentDate))
{
    throw new Exception("Some clear message here.");
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2011-03-01
    • 2016-03-20
    相关资源
    最近更新 更多