EF 批插入

  废话不多说,直接上代码

public void BulkInsert<T>(IList<T> entities,int timeout=0) where T :class
        {
            var con = Database.Connection as SqlConnection;
            if (con == null) return;
            if (con.State != ConnectionState.Open)
                con.Open();
            try {
                string tablename = null, columnname = null;
                var tableattr = typeof(T).GetCustomAttribute<TableAttribute>();
                if (tableattr != null)
                    tablename = tableattr.Name;
                else
                    tablename = typeof(T).Name;
                using (var bulkCopy = new SqlBulkCopy(con) { DestinationTableName = tablename })
                {
                    var properties = typeof(T).GetProperties().Where(p => !p.GetGetMethod().IsVirtual).ToArray();
                    var table = new System.Data.DataTable();
                    foreach (var property in properties)
                    {
                        Type propertyType = property.PropertyType;
                        if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        {
                            propertyType = Nullable.GetUnderlyingType(propertyType);
                        }
                        var columnattr = property.GetCustomAttribute<ColumnAttribute>();
                        if (columnattr != null)
                            columnname = columnattr.Name;
                        else
                            columnname = property.Name;
                        table.Columns.Add(new System.Data.DataColumn(property.Name, propertyType));
                        bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(property.Name, columnname));
                    }
                    foreach (var entity in entities)
                    {
                        table.Rows.Add(properties.Select(p => p.GetValue(entity, null)).ToArray());
                    }
                    if (timeout != 0)
                        bulkCopy.BulkCopyTimeout = timeout;
                    bulkCopy.WriteToServer(table);
                }
            }
            catch (Exception e)
            {
                //System.Diagnostics.Debug.WriteLine(e);
                throw e;
            }
            finally
            {
                con.Close();
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值