C# 如何使用dapper映射/连接两个表并按参数筛选
我想连接两个相互有关系的表, 在客户表中,有两列用于删除和批准。获取已批准但未删除的客户,然后使用CustId将客户与贷款表匹配(两个表都有CustId),并根据提供的参数进行筛选C# 如何使用dapper映射/连接两个表并按参数筛选,c#,sql,sql-server,asp.net-core,dapper,C#,Sql,Sql Server,Asp.net Core,Dapper,我想连接两个相互有关系的表, 在客户表中,有两列用于删除和批准。获取已批准但未删除的客户,然后使用CustId将客户与贷款表匹配(两个表都有CustId),并根据提供的参数进行筛选 已删除=0 批准=1 传递的参数是(并且可以是可选的)用户只能传递一个、两个或多个参数 利率 甘薯 最后付款日期 public async Task<IEnumerable<Loan>> ManageGettingAll(string InterestRate, strin
- 已删除=0
- 批准=1
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;
}
public async Task ManageGettingAll(字符串InterestRate、字符串LoanTrfDate、字符串LastPaymentDate)
{
IEnumerable loans=null;
//var sql=“Select*from MonthlyInterest,其中LoanAccountNo=@Id和Deleted=@Deleted并在@StartDate和@EndDate之间转换(TranDate为DATE)”;
试一试{
使用(var conn=newsqlconnection(connectionstring))
{
等待连接OpenAsync();
var参数=新
{
利率=利率,
LoanTrfDate=LoanTrfDate,
LastPaymentDate=LastPaymentDate
};
string sql=“Select l.*,c.FirstName\u CompanyName from dbo.Loan l left join Customer where and l.Deleted=0 and l.Approved=1 c on l.CustId=c.CustId where InterestRate=@InterestRate and CAST(LoanTrfDate)=@LoanTrfDate and CAST(LastPaymentDate)=@LastPaymentDate”;
loans=await conn.querysync(sql,参数);
}
}
捕获(例外情况除外)
{
投掷;
}
归还贷款;
}
要仅在参数不为null时按参数进行筛选,可以使用下面的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.");
}
需要明确的是,您的问题是如何仅在指定值时按参数过滤?并忽略其参数是否为空?必须至少传递一个参数。您可以使用DynamicParameters对象。您可以检查传递的字符串是否不为null,然后仅将这些字符串添加到DynamicParameters对象。在SQL端,您可以使用ISNULL(@InterestRate,InterestRate)或Coalease函数。