Compare two List and Insert Delete record in database using Entity Framework in ASP.Net

mahesh213
 
on Aug 17, 2020 02:16 AM
Sample_112693.zip
978 Views

Hi,

I have 2 collections in that i have some data

after clicking of save button 

i have one table with some data

DowonlaodTask

Id-primary Key

based upon MachineId i have n no of OperationId's

MachineId     OperationId   Id

1                    1                 1

1                    2                  2

1                     3                 3

 

currently my expected o/p

......................................

MachineId     OperationId   Id

1                    1                  1            

1                    3                  3

1                    5                   4   

 

after clicking of save button 

I am getting some data that i am going to save in one variable

var list2 = new List<DownloadTask>();
list2.Add(new DownloadTask { OperationID = 1, MachineID = 1,Id=1 });
list2.Add(new DownloadTask { OperationID = 3, MachineID = 1,Id=3 });
list2.Add(new DownloadTask { OperationID = 5, MachineID = 1 });

based upon machine Id in Download task I have some data stored in database

could you please help me

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 18, 2020 06:22 AM

Hi mahesh213,

Check this example. Now please take its reference and correct your code.

Code

protected void Page_Load(object sender, EventArgs e)
{
    TestEntities entities = new TestEntities();
    int mId = 1;
    var list2 = new List<Task>();
    list2.Add(new Task { OperationID = 1, MachineID = 1, Id = 1 });
    list2.Add(new Task { OperationID = 3, MachineID = 1, Id = 3 });
    list2.Add(new Task { OperationID = 5, MachineID = 1, Id = 4 });

    var list1 = entities.DownloadTasks.Where(x => x.MachineId == mId).ToList();

    foreach (Task task in list2)
    {
        var exists = list1.Where(x => x.OperationId == task.OperationID).FirstOrDefault();
        if (exists == null)
        {
            DownloadTask dtask = new DownloadTask();
            dtask.Id = task.Id;
            dtask.MachineId = task.MachineID;
            dtask.OperationId = task.OperationID;
            entities.DownloadTasks.Add(dtask);
            entities.SaveChanges();
        }
    }

    var updatedlist1 = entities.DownloadTasks.Where(x => x.MachineId == mId).ToList();
    foreach (DownloadTask task in updatedlist1)
    {
        var exists = list2.Where(x => x.OperationID == task.OperationId).FirstOrDefault();
        if (exists == null)
        {
            entities.DownloadTasks.Remove(task);
            entities.SaveChanges();
        }
    }

}

public class Task
{
    public int MachineID { get; set; }
    public int OperationID { get; set; }
    public int Id { get; set; }
}

Output

 

MachineId OperationId Id
1 1 1
1 3 3
1 5 4