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

2024-03-01 0 501
目录
  • 示例实体
  • 1.自己根据实体生成sql(相对复杂)
  • 2.使用特性跳过属性

我们在使用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字段不映射到数据库内容请搜索悠久资源以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 数据库其它 dapper使用Insert或update时部分字段不映射到数据库 https://www.u-9.cn/database/dataqita/182324.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务