在 Dapper 中並沒有像是 Entity Framework Core 之類的 Column Attribute 可以使用,沒有辦法透過直接在屬性上放上 Attribute 讓 Dapper 認識資料庫的哪個欄位對應到哪個屬性。不過依靠 C# 萬能的 LINQ 還是很簡單就可以把欄位放到對應的位置。
假設一個最簡單的使用者實體如下:
資料庫查詢語法為:
C# 查詢的程式碼如下:
上面程式碼查詢結果應該會發現 UserName 是 null ,因為在資料庫的欄位是 user_name ,中間使用底線隔開,在 Dapper 中找不到相對應的屬性,於是 user_name 無家可歸,而 UserName 也沒有東西。
最簡單的解法如下:
將查詢結果的資料型態設定為 dynamic ,然後手動指定欄位和屬性的對應。
假設一個最簡單的使用者實體如下:
public class UserEntity
{
public int Id { get; set; }
public string UserName { get; set; }
}
資料庫查詢語法為:
select id, user_name from users;
C# 查詢的程式碼如下:
string connectionString = "Server=192.168.0.2,1433;Database=my_database;User Id=sa;Password=password;";
using var connection = new SqlConnection(connectionString);
List<UserEntity> list = connection
.Query<UserEntity>("select id, user_name from users")
.ToList();
上面程式碼查詢結果應該會發現 UserName 是 null ,因為在資料庫的欄位是 user_name ,中間使用底線隔開,在 Dapper 中找不到相對應的屬性,於是 user_name 無家可歸,而 UserName 也沒有東西。
最簡單的解法如下:
string connectionString = "Server=192.168.0.2,1433;Database=my_database;User Id=sa;Password=password;";
using var connection = new SqlConnection(connectionString);
List<UserEntity> list = connection.Query<dynamic>("select id, user_name from users")
.Select(x => new UserEntity()
{
Id = x.id,
UserName = x.user_name,
}
)
.ToList();
將查詢結果的資料型態設定為 dynamic ,然後手動指定欄位和屬性的對應。
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com