dapper使用Insert或update時部分字段不映射到數據庫
更新時間:2023年12月14日 10:07:24 作者:香煎三文魚
我們在使用dapper的insert或update方法時可能會遇見一些實體中存在的字段但是,數據庫中不存在的字段,這樣在使用insert時就是拋出異常提示字段不存在,這個時候該怎么解決呢,下面給大家分享示例實體代碼,感興趣的朋友一起看看吧
我們在使用dapper的insert或update方法時可能會遇見一些實體中存在的字段但是,數據庫中不存在的字段,這樣在使用insert時就是拋出異常提示字段不存在,這個時候該怎么解決呢,下面一起看一下:
示例實體
這里我們假如 test字段在數據庫中不存在
[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.自己根據實體生成sql(相對復雜)
這里我們可以通過反射獲取實體的屬性,去判斷忽略不需要的字段
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; } 然后直接調用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);
}
}到此這篇關于dapper使用Insert或update時部分字段不映射到數據庫的文章就介紹到這了,更多相關dapper字段不映射到數據庫內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Sql Server 和 Access 操作數據庫結構Sql語句小結
Sql Server 和 Access 操作數據庫結構Sql語句小結...2007-06-06

