dapper使用Insert或update時部分字段不映射到數(shù)據(jù)庫
我們在使用dapper的insert或update方法時可能會遇見一些實體中存在的字段但是,數(shù)據(jù)庫中不存在的字段,這樣在使用insert時就是拋出異常提示字段不存在,這個時候該怎么解決呢,下面一起看一下:
示例實體
這里我們假如 test字段在數(shù)據(jù)庫中不存在
[Table("DemoTable")]
public class DemoTable:BaseEntity,ISoftDelete
{
public bool isDelete { get; set; }
[Key]
[Comment("主鍵")]
public int id { get; set; }
[Comment("姓名")]
[MaxLength(20)]
public string name { get; set; }
[Comment("身份證號")]
[MaxLength(18)]
public string idCard { get; set; }
public string test { get; set; }
}1.自己根據(jù)實體生成sql(相對復(fù)雜)
這里我們可以通過反射獲取實體的屬性,去判斷忽略不需要的字段
private string GetTableName() => typeof(T).Name;
public async Task<int> CreateAsync(T entity)
{
try
{
using IDbConnection db = GetOpenConn();
var type = entity.GetType();
//在這里我們略過了 id 和test 字段,這樣在生成sql時就不會包含
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(prop => !string.IsNullOrWhiteSpace(prop.GetValue(entity))&& prop.Name != "id" && prop.Name != "test ");
var columns = string.Join(", ", properties.Select(prop => prop.Name));
var values = string.Join(", ", properties.Select(prop => $"@{prop.Name}"));
var query = $"INSERT INTO {GetTableName()} ({columns}) VALUES ({values})";
return Convert.ToInt32(await db.QueryAsync(query, entity));
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}2.使用特性跳過屬性
使用特性的方式就非常簡單粗暴啦,引用using Dapper.Contrib.Extensions;
在不需要的映射的屬性上添加[Write(false)]
using Dapper.Contrib.Extensions;
[Write(false)]
public int id { get; set; }
[Write(false)]
public string test { get; set; }
using Dapper.Contrib.Extensions;
[Write(false)]
public int id { get; set; }
[Write(false)]
public string test { get; set; } 然后直接調(diào)用Insert方法即可
public async Task<int> CreateAsync(T entity)
{
try
{
using IDbConnection db = GetOpenConn();
return db.Insert<T>(entity);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}到此這篇關(guān)于dapper使用Insert或update時部分字段不映射到數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)dapper字段不映射到數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
虛擬主機ACCESS轉(zhuǎn)換成MSSQL完全攻略(圖文教程)
大家都知道,ACCESS數(shù)據(jù)庫在數(shù)據(jù)量到達一定程度后,訪問速度會明顯變慢,甚至造成崩潰。目前,大多數(shù)虛擬主機服務(wù)商提供的ASP主機空間一般都同時支持MS ACCESS和MS SQL兩種類型的數(shù)據(jù)庫。2010-04-04
Sql Server 和 Access 操作數(shù)據(jù)庫結(jié)構(gòu)Sql語句小結(jié)
Sql Server 和 Access 操作數(shù)據(jù)庫結(jié)構(gòu)Sql語句小結(jié)...2007-06-06
StarRocks數(shù)據(jù)庫詳解(什么是StarRocks)
StarRocks是一個高性能的全場景MPP數(shù)據(jù)庫,支持多種數(shù)據(jù)導(dǎo)入導(dǎo)出方式,包括Spark、Flink、Hadoop等,它采用分布式架構(gòu),支持多副本和彈性容錯,本文介紹StarRocks詳解,感興趣的朋友一起看看吧2025-03-03
高性能分析數(shù)據(jù)庫StarRocks的安裝與使用詳解
在大數(shù)據(jù)時代,選擇一個高性能的分析數(shù)據(jù)庫對業(yè)務(wù)的成功至關(guān)重要,StarRocks作為一款次世代MPP數(shù)據(jù)庫,以其卓越的實時分析和多維分析能力而聞名,下面小編就來和大家聊聊它的具體安裝與使用吧2025-03-03

