我有两个模型:
public class RuleValidation
{
public int RuleId { get; set; }
public string RuleName { get; set; }
public int ClientId { get; set; }
public string ClientName { get; set; }
public List<RuleException> RuleExcpetions { get; set; }
}
和:
public class RuleException
{
public int ExceptionId { get; set; }
public int RuleId { get; set; }
public string ExceptionValue { get; set; }
public string ExcpetionResult { get; set; }
}
我正在使用以下查询来加载模型:
public async Task<RuleValidation> GetRulesByClient(string clientId)
{
using (IDbConnection conn = Connection)
{
string sQuery = @"SELECT
Client.Id as 'ClientName',
Client.ClientName,
Rules.Id,
Rules.RuleName,
Rules.Code,
RuleException.ExceptionValue,
RuleException.ExceptionResult
FROM
Rules
LEFT OUTER JOIN
RuleException ON Rules.Id = RuleException.RuleId
RIGHT OUTER JOIN
Client ON Rules.Id = Client.RuleId
WHERE
Client.ClientName = @CLIENTID";
conn.Open();
var result = await conn.QueryAsync<RuleValidation>(sQuery, new { CLIENTID = clientId });
return (RuleValidation)result;
}
}
这似乎将查询反序列化为RuleValidation对象,但是对于那些具有异常的记录,不会加载RuleException对象。所以我试图这样修改收益:
var return= conn.QueryAsync<RuleValidation, RuleException>(
sQuery,
(ruleValidation, ruleException) =>
{
ruleValidion.RuleException = ruleException;
return return;
},
splitOn: "RuleId");
但是我得到一个错误:
IDBCOnnection不包含QueryAsync的定义,并且找不到可访问的扩展方法,该方法接受类型为'IDBConnection'的第一个参数
这是我建立连接的方式(它确实适用于初始查询)
public IDbConnection Connection
{
get
{
return new SqlConnection(_configuration.GetConnectionString("ValidationRulesConnectionString"));
}
}
我是dapper的新手,使用它没有问题,但这是我遇到的第一个问题,我似乎无法在dapper教程中或在线寻找解决方案。
答案 0 :(得分:2)
您的QueryAsync
呼叫缺少返回类型。它需要3个参数-要映射的两个对象,然后是返回类型。您还需要将异常添加到列表中:
var return= conn.QueryAsync<RuleValidation, RuleException, RuleValidation>(
sQuery,
(ruleValidation, ruleException) =>
{
if(ruleException != null)
{
ruleValidation.RuleExceptions.Add(ruleException);
}
return ruleValidation;
},
splitOn: "RuleId");
并确保您的RuleValidation
类初始化列表属性
public class RuleValidation
{
public int RuleId { get; set; }
public string RuleName { get; set; }
public int ClientId { get; set; }
public string ClientName { get; set; }
public List<RuleException> RuleExcpetions { get; set; } = new List<RuleException>();
}
有一个示例here