欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

dapper使用Insert或update時(shí)部分字段不映射到數(shù)據(jù)庫(kù)

 更新時(shí)間:2023年12月14日 10:07:24   作者:香煎三文魚  
我們?cè)谑褂胐apper的insert或update方法時(shí)可能會(huì)遇見一些實(shí)體中存在的字段但是,數(shù)據(jù)庫(kù)中不存在的字段,這樣在使用insert時(shí)就是拋出異常提示字段不存在,這個(gè)時(shí)候該怎么解決呢,下面給大家分享示例實(shí)體代碼,感興趣的朋友一起看看吧

我們?cè)谑褂胐apper的insert或update方法時(shí)可能會(huì)遇見一些實(shí)體中存在的字段但是,數(shù)據(jù)庫(kù)中不存在的字段,這樣在使用insert時(shí)就是拋出異常提示字段不存在,這個(gè)時(shí)候該怎么解決呢,下面一起看一下:

示例實(shí)體

這里我們假如 test字段在數(shù)據(jù)庫(kù)中不存在

[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("身份證號(hào)")]
    [MaxLength(18)]
    public string idCard { get; set; }
    public string test { get; set; } 
}

1.自己根據(jù)實(shí)體生成sql(相對(duì)復(fù)雜)

這里我們可以通過反射獲取實(shí)體的屬性,去判斷忽略不需要的字段

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時(shí)就不會(huì)包含
        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.使用特性跳過屬性

使用特性的方式就非常簡(jiǎn)單粗暴啦,引用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í)部分字段不映射到數(shù)據(jù)庫(kù)的文章就介紹到這了,更多相關(guān)dapper字段不映射到數(shù)據(jù)庫(kù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論