Say I have a database with these entries in the people
table:
id | companyId | name
1 | 9 | Kevin
2 | 9 | Mike
3 | 9 | John
I then get this put
request to update the entities:
[
{"id": 1, "name": "Kevin"},
{"id": 2, "name": "Michael"},
{"id": 0, "name": "Joe"}
]
So, I need to Update id 2, remove id 3, and add the new entity. I know _context.People.UpdateRange(entities)
will update the existing entities and add the new ones, but I also need to remove id 3. Basically, the content of the json request should be the entirety of the people table where companyId = 9
. I know I can do this:
var currentPeople = _context.People
.AsNoTracking()
.Where(e => e.companyId == request.companyId)
.ToListAsync();
var requestEntities = request
.Select(m => new PersonEntity(r))
.ToList();
var peopleToRemove = requestEntities
.Where(oldEntity => requestEntities.All(e => e.Id != oldEntity.Id))
.ToList();
using (var transaction = _context.Database.BeginTransaction())
{
_context.People.RemoveRange(peopleToRemove);
_context.People.UpdateRange(requestEntities);
await _context.SaveChangesAsync();
transaction.Commit();
}
But that's super clunky. Does EF Core offer a better solution? Thanks!
You can do as follows:
var existingPeopleList = _context.People.AsNoTracking()
.Where(e => e.companyId == request.companyId)
.ToListAsync();
var requestEntities = request.Select(r => new PersonEntity(r)).ToList();
var requestedPeopleList = requestEntities.Select(re => new People()
{
Id = re.Id,
CompanyId = 9,
Name = re.Name
}).ToList();
var peopleToBeRemoved = existingPeopleList.Where(ep => requestedPeopleList.All(rp => rp.Id != ep.Id)).ToList();
var peopleToBeAdded = requestedPeopleList.Where(rp => existingPeopleList.All(ep => ep.Id != rp.Id)).ToList();
var peopleToBeUpdated = requestedPeopleList.Where(rp => existingPeopleList.Any(ep => ep.Id == rp.Id)).ToList();
_context.People.RemoveRange(peopleToBeRemoved);
_context.People.AddRange(peopleToBeAdded);
_context.People.UpdateRange(peopleToBeUpdated);
await _context.SaveChangesAsync();
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.