简体   繁体   中英

Proper way to update the list of records in table using entity framework

In my Education Programme database table, I have 3 records for one specific student

在此处输入图片说明

so I want to remove P3 program from this person list, so in font-end its showing like like this

在此处输入图片说明

once I click Delete, specific P3 remove from frontend and model and once hit save button it's passing to the backend code P1 , P2 as a list.

I'm using the entity framework for database transactions.

looking for your advice here on

  • Should I delete all existing records and then insert P1 , P2 again. Or
  • DO I need iterate each record by comparing list I'm sending vs existing records and attach P1 , P2 and find out missing one and delete Or
  • this type of transaction can EF do itself

Looking forward which way is recommended

I would suggest you to go for second option since its better approach to remove missing records rather than remove all records.

'Missing' items from a collection are not considered to be deleted.

So what you'll need to do is mark the items for deletion yourself. Something like this:

public void Update(Programme record)
{
    var missingRows = dB.ProgrammeRows.Where(i => i.ProgrammeId == record.ProgrammeId)
                        .Except(record.Rows);
    dB.ProgrammeRows.RemoveRange(missingRows);

    dB.Programmes.Update(record);
    dB.SaveChanges();
}

And the class should be as follows:

   public class ProgrammeRow
   {
        public int ProgrammeId { get; set; }
        public string ProgrammeName { get; set; }
        public int StudentId { get; set; }
        public virtual Student Student{ get; set; }
   }

   public class Programme
   {
        public int ProgrammeId { get; set; }
        private ICollection<ProgrammeRow> _rows;
        public virtual ICollection<ProgrammeRow> Rows => _rows ?? (_rows = new List<ProgrammeRow>());
   }

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