記一次使用dapper的坑(數據庫與類映射)(轉)


本來是測試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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM