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