netcore sqlsugar 实现不插入重复数据多条数据
可以使用 SqlSugar 的 BulkInsert 方法实现批量插入数据,并在插入时通过判断数据是否已存在来过滤掉重复数据。具体步骤如下:
- 使用 Select 方法查询已存在的数据的主键列表。
var db = new SqlSugarClient(new ConnectionConfig
{
ConnectionString = "your_connection_string",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
var existingKeys = db.Queryable<YourEntity>()
.Select(entity => entity.PrimaryKey)
.ToList();
- 过滤掉已存在的主键,得到待插入的数据列表。
var toInsert = new List<YourEntity>();
foreach (var entity in yourEntities)
{
if (!existingKeys.Contains(entity.PrimaryKey))
{
toInsert.Add(entity);
}
}
- 使用 BulkInsert 方法批量插入待插入的数据。
db.BulkInsert(toInsert);
完整代码示例:
var db = new SqlSugarClient(new ConnectionConfig
{
ConnectionString = "your_connection_string",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
var existingKeys = db.Queryable<YourEntity>()
.Select(entity => entity.PrimaryKey)
.ToList();
var toInsert = new List<YourEntity>();
foreach (var entity in yourEntities)
{
if (!existingKeys.Contains(entity.PrimaryKey))
{
toInsert.Add(entity);
}
}
db.BulkInsert(toInsert);
``
原文地址: https://www.cveoy.top/t/topic/fnAT 著作权归作者所有。请勿转载和采集!