entity framework update multiple records using join

entity-framework entity-framework-core linq

Question

I'm trying to update multiple records using entity framework, but am not sure how to proceed.

Basic setup:

class Appointment
{
    public int Id {get; set;}
    public double Charge {get; set;}
    public DateTime Time {get; set;}
}

The view presents a list of appointments, and then the call to controller Post action passes in an Ienumerable<Appointment>.

public async Task<int> UpdateAppointments(IEnumerable<Appointment> appointments){
    // code goes here
    var appointmentsToUpdate = await _context
           .Appointments
           .Where(a => a.time > DateTime.Now).ToListAsync();

    // what to do here??
    // loop through appointmentsToUpdate and find the relevant 
    // record inside appointment, and then do an update? 
    // Seems like a merge would be more efficient.

}

What i want to do is merge appointments and appointmentsToUpdate and update the appointment time. In another scenario, with a different authorization, I want the administrator, for example, to only be able to change the appointment charge, so deleting all records and appending the new records isn't an option.

It seems like you can do this with pure sql statements, but then the appointments parameter is passed in as an IEnumerable, not as a table already in the database as in this answer: Bulk Record Update with SQL

First of all, can you do this kind of update using Linq? Does it translate directly to entity framework (core)?

1
0
2/8/2018 8:03:46 PM

Popular Answer

Without extension projects or store SQL the best you can do is to attach the Appointments as unchanged entities, and mark the target property as modified.

The Appointments you attach just need the Key Properties and the Time populated.

Like this:

class Db : DbContext
{

    public DbSet<Appointment> Appointments { get; set; }

    public void UpdateAppointmentTimes(IEnumerable<Appointment> appointments)
    {
        foreach(var a in appointments)
        {
            this.Appointments.Attach(a);
            this.Entry(a).Property(p => p.Time).IsModified = true;
        }
        this.SaveChanges();
    }
     . . .

Which will update only the changed column for all those appointments in a single transaction.

2
2/8/2018 10:31:32 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow