简体   繁体   中英

How to insert multiply items with entity framework and linq

I have an asp net web project and i try to insert multiply records to my base.
My idea is update records, and make copy of this records , with updated parameters.
But my records updates only , i don't understand how to make multiply insert ( i don't want to make foreach and insert/update by 1 record) .
HOW CAN I MAKE UPDATE OF RECORDS AND AFTER THAT INSERT COPY OF THIS RECORDS WITH 1 CHANGED PARAMETER ?

My code:

  public void SAVE(List<int> list,int stat )
        {
            var all = context.ReqForDoc.ToList();
            var friends = context.ReqForDoc.Where(f => list.Contains(f.requestN)).ToList();

            friends.ForEach(a => // UPDATE WORK
            {
                a.actual = 0;
                a.ReqStatus = stat;
                a.ChangeDate = DateTime.Now;
            });

            all.AddRange(friends); // INSERT NOW WORK

            context.SaveChanges();
        }

I found a solution. Thanks @ Ivan Stoev for solution. I create new object and use AddRange for insert new rows .

public void SAVE(List<int> list )

        {  
var all = context.ReqForDoc.ToList();
                var friends = context.ReqForDoc.Where(f => list.Contains(f.requestN)).ToList();
                friends.ForEach(a =>
                {
                    a.actual = 0;
                });

                 context.SaveChanges(); // UPDATE RECORDS

               List<ReqInf> list2 = new List<ReqInf>(); 
                list2 = context.ReqForDoc.Where(f => list.Contains(f.requestN)).ToList();
                context.ReqForDoc.AddRange(list2); //INSERT NEW
                list2.ForEach(a =>
                {
                    a.actual = 1;
                    if (a.Status == 3) { a.Status = 92; }



                });   //UPDATE INSERTED
                context.SaveChanges(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM