我们在使用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字段不映射到数据库内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源:https://www.jb51.net/database/3078851ut.htm
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |
|