自定義對映

如果查詢列名稱與你的類不匹配,則可以設定型別的對映。此示例演示了使用 System.Data.Linq.Mapping.ColumnAttributeas 作為自定義對映的對映。

對映只需要為每個型別設定一次,因此在應用程式啟動時或在其他地方設定它們僅初始化一次。

假設再次使用與一對多示例相同的查詢,並將類重構為更好的名稱,如下所示:

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<> 示例執行查詢。

此答案中顯示了新增對映的更簡單方法。