Home > Blockchain >  How to insert to database in bulk instead of inserting it 1 by 1
How to insert to database in bulk instead of inserting it 1 by 1

Time:03-17

How do you make the list receives more than 1 value based on the quantity of the SelectedList.Count.

Code:

 for (int i = 0; i < SelectedList.Count; i  )
            {
                lastSeriesNo  ;

                string assetcodegen = string.Format("{0}-{1}-{2}", List[i].AssetCategoryID, CurrentApplication.Now.Year, lastSeriesNo.ToString().PadLeft(5, '0'));
                AssetCodeOfficial[i] = assetcodegen;


                var list = (from x in ctx.DataContext.AssetRegistryEntities
                            where x.AssetCode == SelectedList[i].AssetCode
                            select x
                            ).AsEnumerable();

                foreach (var asset in list)
                {
                    asset.SeriesNumber = (short)lastSeriesNo;
                    asset.Status = 'A';
                    asset.IsTemp = false;
                    asset.UpdatedBy = CurrentApplication.CurrentUserId;
                    asset.UpdatedDate = asset.AssetCreatedDate = CurrentApplication.Now;
                    AssetCodetemp[i] = asset.AssetCode;
                    depreciationInMonths = asset.DepnInMonths;

                    ctx.DataContext.SubmitChanges();
                }

            }

CodePudding user response:

Thank you all guys for the help, I manage to fix my problem. It already saves the data to the database as bulk not 1 by 1 saving.

So I use lambda expression for my list and use the .addRange to add item to the list. list.AddRange(ctx.DataContext.AssetRegistryEntities.Where(x=>x.AssetCode.Trim() == SelectedList[i].AssetCode.Trim()));

Code:

List<NXpert.FixedAsset.DataAccess.AssetRegistryEntity> list = new List<NXpert.FixedAsset.DataAccess.AssetRegistryEntity>();

                for (int i = 0; i < SelectedList.Count; i  )
                {
                    lastSeriesNo  ;

                    string assetcodegen = string.Format("{0}-{1}-{2}", List[i].AssetCategoryID, CurrentApplication.Now.Year, lastSeriesNo.ToString().PadLeft(5, '0'));
                    AssetCodeOfficial[i] = assetcodegen;

                    list.AddRange(ctx.DataContext.AssetRegistryEntities.Where(x=>x.AssetCode.Trim() == SelectedList[i].AssetCode.Trim()));
                    AssetCodetemp[i] = list[i].AssetCode;
                }

                foreach (var asset in list)
                {
                    asset.SeriesNumber = (short)lastSeriesNo;
                    asset.Status = 'A';
                    asset.IsTemp = false;
                    asset.UpdatedBy = CurrentApplication.CurrentUserId;
                    asset.UpdatedDate = asset.AssetCreatedDate = CurrentApplication.Now;
                    depreciationInMonths = asset.DepnInMonths;
                }
                ctx.DataContext.SubmitChanges();
  • Related