記一次使用dapper的坑(資料庫與類對映)(轉)
阿新 • • 發佈:2021-10-27
本來是測試dapper轉換真正的mysql語句後是否能真正使用索引的,不過被一個地方卡住了,在查詢的時候一直不能對映強型別的值。找了大概1小時才找到處理的方式,記錄下來免得忘記。
先看錶設計
image.png
類定義,因為程式如果使用下劃線感覺會很突兀,不符合C#類命名規範,所以統一使用了大寫開頭的駝峰式命名,找了一個通過Attribute的對映到資料庫欄位的方式,程式碼在最後貼上
public class PersonInfo
{
[Column(Name = "mainid")]
public long MainId { get; set; }
[Column(Name = "id_card_number")]
public string IdCardNumber { get; set; }
[Column(Name = "name")]
public string Name { get; set; }
[Column(Name = "created_datetime")]
public DateTime CreatedDateTime { get; set; }
}
先插入資料,通過dapper插入資料是沒啥問題的,看看資料
image.png
程式碼也是正常,即使不指定列,只要多傳入一個MainId也是能正常插入資料的
static void Main(string[] args)
{
string connectionString = @"server=localhost;port=3306;database=tor_db_test;user=root;Password=123456;CharSet=utf8mb4;Pooling=true;Min Pool Size=0;Max Pool Size=100;";
using (IDbConnection connection = new MySqlConnection(connectionString))
{
var resultInt = connection.Execute("INSERT INTO person_info VALUES (@MainId,@IdCardNumber,@Name,@CreatedDateTime)", new PersonInfo()
{
MainId = 2,
IdCardNumber = "440684200001010000",
Name = "嗚嗚嗚",
CreatedDateTime = DateTime.Now
});
Console.WriteLine(resultInt);
}
Console.WriteLine();
Console.ReadLine();
}
但是查詢就有問題了
static void Main(string[] args)
{
string connectionString = @"server=localhost;port=3306;database=tor_db_test;user=root;Password=123456;CharSet=utf8mb4;Pooling=true;Min Pool Size=0;Max Pool Size=100;";
using (IDbConnection connection = new MySqlConnection(connectionString))
{
//var p = connection.Query<PersonInfo>("SELECT * FROM person_info ");
var p = connection.Query<PersonInfo>("SELECT mainid,id_card_number,name,created_datetime FROM person_info ");
Console.WriteLine(JsonConvert.SerializeObject(p, Formatting.Indented));
}
Console.WriteLine();
Console.ReadLine();
}
查詢結果如下,強型別查詢無法自動匹配值了
image.png
試一下動態型別,正常的,所以問題定位在dapper強型別轉換沒能匹配上
image.png
最後發現有這個配置,主要是忽略下劃線再進行匹配
Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
加上之後就正常了
image.png
程式碼如下
static void Main(string[] args)
{
string connectionString = @"server=localhost;port=3306;database=tor_db_test;user=root;Password=123456;CharSet=utf8mb4;Pooling=true;Min Pool Size=0;Max Pool Size=100;";
using (IDbConnection connection = new MySqlConnection(connectionString))
{
Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
var p = connection.Query<PersonInfo>("SELECT mainid,id_card_number,name,created_datetime FROM person_info ");
Console.WriteLine(JsonConvert.SerializeObject(p, Formatting.Indented));
}
Console.WriteLine();
Console.ReadLine();
}
通過Attribute對映程式碼,網上找的,麼得註釋
/// <summary>
/// Uses the Name value of the <see cref="ColumnAttribute"/> specified to determine
/// the association between the name of the column in the query results and the member to
/// which it will be extracted. If no column mapping is present all members are mapped as
/// usual.
/// </summary>
/// <typeparam name="T">The type of the object that this association between the mapper applies to.</typeparam>
public class ColumnAttributeTypeMapper<T> : FallbackTypeMapper
{
public ColumnAttributeTypeMapper()
: base(new SqlMapper.ITypeMap[]
{
new CustomPropertyTypeMap(
typeof(T),
(type, columnName) =>
type.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(false)
.OfType<ColumnAttribute>()
.Any(attr => attr.Name == columnName)
)
),
new DefaultTypeMap(typeof(T))
})
{
}
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class ColumnAttribute : Attribute
{
public string Name { get; set; }
}
public class FallbackTypeMapper : SqlMapper.ITypeMap
{
private readonly IEnumerable<SqlMapper.ITypeMap> _mappers;
public FallbackTypeMapper(IEnumerable<SqlMapper.ITypeMap> mappers)
{
_mappers = mappers;
}
public ConstructorInfo FindConstructor(string[] names, Type[] types)
{
foreach (var mapper in _mappers)
{
try
{
ConstructorInfo result = mapper.FindConstructor(names, types);
if (result != null)
{
return result;
}
}
catch (NotImplementedException)
{
}
}
return null;
}
public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName)
{
foreach (var mapper in _mappers)
{
try
{
var result = mapper.GetConstructorParameter(constructor, columnName);
if (result != null)
{
return result;
}
}
catch (NotImplementedException)
{
}
}
return null;
}
public SqlMapper.IMemberMap GetMember(string columnName)
{
foreach (var mapper in _mappers)
{
try
{
var result = mapper.GetMember(columnName);
if (result != null)
{
return result;
}
}
catch (NotImplementedException)
{
}
}
return null;
}
public ConstructorInfo FindExplicitConstructor()
{
return _mappers
.Select(mapper => mapper.FindExplicitConstructor())
.FirstOrDefault(result => result != null);
}
}
完
連結:https://www.jianshu.com/p/ea588d837014