假设我正在使用 Dapper 运行标准选择查询,以使用存储过程填充对象。
public IEnumerable<Person> GetPeople()
{
IEnumerable<Person> people;
using (var con = new SqlConnection(connectionString))
{
people = con.Query<Person>("[dbo].[sp_Select_People]", commandType: CommandType.StoredProcedure);
}
return people;
}
Person 类定义为:
public class Person
{
public string Name{ get; set; }
public string Age{ get; set; }
public string Date { get; set; }
public string Error{ get; set; }
假设被调用的存储过程是
从...中选择年龄、日期、错误、姓名
Dapper 将以什么顺序填充类对象:
- 姓名、年龄、日期、错误 - 基于 C# 类定义
- 年龄、日期、错误、名称 - 基于 SQL 查询定义
- 随机
- 一些其他类型的优化
根据使用断点的个人测试,答案似乎是随机的或一些我无法弄清楚的未知优化方案。这是可配置的吗?
我对理论问题更感兴趣,但就上下文而言,提示这个问题的“为什么”是确定最后填充哪个,以便根据其他成员的值设置 Error 属性:
private string _date/_age/_name/etc; <---- whichever property is populated last
public string Date/Age/Name
{
get { return _date; }
set
{
_date = value;
SetError();
}
}
private void SetError()
{
//if (Name == something && Age == something) Error = "x"
//if (etc...
}
最佳答案
Dapper 按照从左到右的顺序处理列,与 CommandBehavior.SequentialAccess 的规则一致 - 并立即存储值。所以:查询列顺序。
如果存在映射到查询的自定义构造函数,事情会变得稍微更复杂,但是,a:只有一点点,而b:这并不适用于此。
关于c# - 运行选择查询时,Dapper 以什么顺序填充类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75725611/