Dapper 批量添加

1、方法一
Controller控制器,代码如下
public ActionResult SaveAction()
{
    List list = new List();
    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 listModel)
{
    try
    {
        if (listModel != null && listModel.Count > 0)
        {
            T model = listModel.FirstOrDefault();
            var ps = model.GetType().GetProperties();
            List @colms = new List();
            List @params = new List();

            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
{
    #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; }
}


你可能感兴趣的:(Dapper)