dapper使用Insert或update时部分字段不映射到数据库

我们在使用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; } 

然后直接调用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);
    }
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-15 12:00:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-15 12:00:03       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-15 12:00:03       82 阅读
  4. Python语言-面向对象

    2023-12-15 12:00:03       91 阅读

热门阅读

  1. Spring Boot 常用注解分类

    2023-12-15 12:00:03       52 阅读
  2. axios跨域问题, 这种情况下 withCredentials 不能为true

    2023-12-15 12:00:03       60 阅读
  3. 746.使用最小花费爬楼梯

    2023-12-15 12:00:03       60 阅读
  4. C# DataTable 总结常用方法

    2023-12-15 12:00:03       52 阅读
  5. C# 德语法语解析浮点数不正确的问题记录

    2023-12-15 12:00:03       67 阅读
  6. 解析Python的Lambda函数:【理解】与【运用】

    2023-12-15 12:00:03       52 阅读
  7. 关于C#反射概念,附带案例!

    2023-12-15 12:00:03       62 阅读
  8. Go并发编程:保障安全与解锁奥秘

    2023-12-15 12:00:03       61 阅读
  9. 异常处理返回结构体,做到全局统一

    2023-12-15 12:00:03       67 阅读
  10. electron这样使用更安全

    2023-12-15 12:00:03       95 阅读