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

我们在使用dapper的insert或update方法时可能会遇见一些实体中存在的字段但是,数据库中不存在的字段,这样在使用insert时就是抛出异常提示字段不存在,这个时候该怎么解决呢,下面一起看一下:

示例实体

这里我们假如 test字段在数据库中不存在

csharp 复制代码
[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(相对复杂)

这里我们可以通过反射获取实体的属性,去判断忽略不需要的字段

csharp 复制代码
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)]

csharp 复制代码
using Dapper.Contrib.Extensions;


	[Write(false)]
	public int id { get; set; }
	[Write(false)]
    public string test { get; set; } 

然后直接调用Insert方法即可

csharp 复制代码
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);
    }
}
相关推荐
Damon小智2 个月前
C#进阶-轻量级ORM框架Dapper的使用教程与原理详解
开发语言·c#·.net·orm·dapper
06111631 年前
Dapper.Lite 扩展
orm·dapper·dbhelper