如果查询列名称与您的类不匹配,则可以设置类型的映射。此示例演示了使用System.Data.Linq.Mapping.ColumnAttribute以及自定义映射的映射。
每种类型的映射仅需要设置一次,因此可以在应用程序启动时或在其他地方设置它们,使其仅初始化一次。
再次假设查询与一对多示例相同,并且将类重构为更好的名称,如下所示:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Born { get; set; }
public Country Residience { get; set; }
public ICollection<Book> Books { get; set; }
}
public class Country
{
[System.Data.Linq.Mapping.Column(Name = "CountryId")]
public int Id { get; set; }
[System.Data.Linq.Mapping.Column(Name = "CountryName")]
public string Name { get; set; }
}
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
}注意如何Book不依赖,ColumnAttribute但我们需要维护该if语句
现在,将此映射代码放置在应用程序中仅执行一次的位置:
Dapper.SqlMapper.SetTypeMap(
typeof(Country),
new CustomPropertyTypeMap(
typeof(Country),
(type, columnName) =>
type.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(false)
.OfType<System.Data.Linq.Mapping.ColumnAttribute>()
.Any(attr =>attr.Name== columnName)))
);
var bookMap = new CustomPropertyTypeMap(
typeof(Book),
(type, columnName) =>
{
if(columnName == "BookId")
{
return type.GetProperty("Id");
}
if (columnName == "BookName")
{
return type.GetProperty("Name");
}
throw new InvalidOperationException($"No matching mapping for {columnName}");
}
);
Dapper.SqlMapper.SetTypeMap(typeof(Book), bookMap);然后使用前面的任何Query<>示例执行查询。
此答案中显示了一种添加映射的更简单方法。