How to do a Bulk Insert — Linq to Entities

前端 未结 4 1054
北海茫月
北海茫月 2020-11-27 16:23

I cannot find any examples on how to do a Bulk/batch insert using Linq to Entities. Do you guys know how to do a Bulk Insert?

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 16:32

    For inserting a huge amount of data in a database, I used to collect all the inserting information into a list and convert this list into a DataTable. I then insert that list to a database via SqlBulkCopy.

    Where I send my generated list
    LiMyList
    which contain information of all bulk data which I want to insert to database
    and pass it to my bulk insertion operation

    InsertData(LiMyList, "MyTable");
    

    Where InsertData is

     public static void InsertData(List list,string TabelName)
            {
                    DataTable dt = new DataTable("MyTable");
                    clsBulkOperation blk = new clsBulkOperation();
                    dt = ConvertToDataTable(list);
                    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                    using (SqlBulkCopy bulkcopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["SchoolSoulDataEntitiesForReport"].ConnectionString))
                    {
                        bulkcopy.BulkCopyTimeout = 660;
                        bulkcopy.DestinationTableName = TabelName;
                        bulkcopy.WriteToServer(dt);
                    }
            }    
    
    public static DataTable ConvertToDataTable(IList data)
            {
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
                DataTable table = new DataTable();
                foreach (PropertyDescriptor prop in properties)
                    table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
                foreach (T item in data)
                {
                    DataRow row = table.NewRow();
                    foreach (PropertyDescriptor prop in properties)
                        row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                    table.Rows.Add(row);
                }
                return table;
            }
    

提交回复
热议问题