Dapper 批量添加、修改

1、方法一
Controller控制器,代码如下

public ActionResult SaveAction()
{
    List<Languages> list = new List<Languages>();
    for (int i = 0; i <= 10; i++)
    {
        var item = new Languages
        {
            Title = "Title" + i.ToString(),
            EnglishTitle = "EnglishTitle",
            CreateBy = 0,
            CreatedDate = DateTime.Now,
            ModifiedBy = 0,
            UpdatedDate = DateTime.Now,
            State = "A"
        };
        list.Add(item);
    }
    _languageSvc.AddBatch(list);
    return View();
}

RepositoryBase基类,代码如下

public virtual void AddBatch(List<T> listModel)
{
    try
    {
        if (listModel != null && listModel.Count > 0)
        {
            T model = listModel.FirstOrDefault();
            var ps = model.GetType().GetProperties();
            List<string> @colms = new List<string>();
            List<string> @params = new List<string>();

            foreach (var p in ps)
            {
                if (!p.CustomAttributes.Any(x => x.AttributeType == typeof(PrimaryKeyAttribute)) && !p.CustomAttributes.Any(x => x.AttributeType == typeof(DBIgnoreAttribute)))
                {
                    @colms.Add(string.Format("[{0}]", p.Name));
                    @params.Add(string.Format("@{0}", p.Name));
                }
            }
            var sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2})", typeof(T).Name, string.Join(", ", @colms), string.Join(", ", @params));
            using (var _conn = _dbFactory.OpenDbConnection())
            {
                _conn.Execute(sql, listModel, null, null, null);
            }
        }
    }
    catch (Exception ex)
    {
        throw;
    }
}

实体类,代码如下

[Serializable]
public class Languages : IEntityBase<Languages>
{
    #region table
    [PrimaryKey]
    public long ID { get; set; }
    public string Title { get; set; }
    public string EnglishTitle { get; set; }
    public long CreateBy { get; set; }
    public long ModifiedBy { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime UpdatedDate { get; set; }
    public string State { get; set; }
    #endregion

    #region DBIgnore
    [DBIgnore]
    public bool AppStatus { get; set; }
    #endregion
}

2、方法二

public void InsertBatch()
{
    try
    {
        string sqlStr = "INSERT INTO ED_Data(DataKey,FieldName,Value) VALUES (@DataKey,@FieldName,@Value)";
        using (IDbConnection conn = OpenConnection())
        {
            conn.Execute(sqlStr, new[] 
            {
                new { DataKey = "a", FieldName = "name", Value = "000001" },
                new { DataKey = "b", FieldName = "age", Value = "000002" },
                new { DataKey = "c", FieldName = "phone", Value = "000003" },
            }, null, null, null);
        }
    }
    catch (Exception)
    {
        throw;
    }
}

实体类,代码如下

public class ED_Data
{
    public string TableName { get; set; }
    public string DataKey { get; set; }
    public string FieldName { get; set; }
    public string Value { get; set; }
}

*
*
*
批量修改
Controller

[HttpPut("update_first_score")]
public ActionResult UpdateFirstScore([FromBody]UpdateFirstScoreRequest request)
{
    List<QualityScoreDto> updateList = new List<QualityScoreDto>();
    updateList.Add(new QualityScoreDto { quality_score_code = 1, first_score = 10 });
    updateList.Add(new QualityScoreDto { quality_score_code = 2, first_score = 20 });
    updateList.Add(new QualityScoreDto { quality_score_code = 3, first_score = 30 });
    _qualityScoreRepo.UpdateFirstScore(request.list);
    return Ok();
}

Repository

public int UpdateFirstScore(List<QualityScoreDto> list)
{
    string sql = "UPDATE trans_quality_score SET first_score=@first_score WHERE quality_score_code=@quality_score_code";
    int result = _conn.Execute(sql, list);
    return result;
}

Request

public class UpdateFirstScoreRequest
{
    public List<QualityScoreDto> list { get; set; }
}

Postman


 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在C#中使用Dapper进行事务批量操作,可以按照以下步骤进行: 1. 开启事务:使用Dapper的Transaction属性可以开启事务。 ``` using (var cn = new SqlConnection(connectionString)) { cn.Open(); using (var transaction = cn.BeginTransaction()) { try { // 执行批量操作 transaction.Commit(); } catch { transaction.Rollback(); throw; } } } ``` 2. 执行批量操作:使用Dapper的Execute方法可以执行批量操作。 ``` using (var cn = new SqlConnection(connectionString)) { cn.Open(); using (var transaction = cn.BeginTransaction()) { try { string sql = "INSERT INTO MyTable (Column1, Column2) VALUES (@Column1, @Column2)"; List<MyData> data = new List<MyData>(); // 添加数据到data列表中 cn.Execute(sql, data, transaction); transaction.Commit(); } catch { transaction.Rollback(); throw; } } } ``` 其中,MyData是一个自定义的数据模型,包含要插入到数据库中的数据。 3. 使用SqlBulkCopy进行批量操作:Dapper也支持使用SqlBulkCopy进行批量操作,可以提高批量操作的效率。 ``` using (var cn = new SqlConnection(connectionString)) { cn.Open(); using (var transaction = cn.BeginTransaction()) { try { using (var bulkCopy = new SqlBulkCopy(cn, SqlBulkCopyOptions.Default, transaction)) { bulkCopy.DestinationTableName = "MyTable"; DataTable table = new DataTable(); // 添加数据到table中 bulkCopy.WriteToServer(table); } transaction.Commit(); } catch { transaction.Rollback(); throw; } } } ``` 以上就是使用Dapper进行事务批量操作的基本步骤。需要注意的是,批量操作可能会影响数据库性能,应该在适当的时候进行优化。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值