Kelum
Kelum

Reputation: 1775

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

enter image description here

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

enter image description here

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

Looking forward which way is recommended

Upvotes: 0

Views: 584

Answers (1)

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

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>());
   }

Upvotes: 2

Related Questions