简体   繁体   中英

C# Entity - Delete Items by ID - ID to delete are in an other list

I need to delete items in a collection managed by Entity 6. The items that have to be deleted are in an other list

Currently I do this :

 idToDelete = model.Courses.Where(x => x.Deleted).Select(x => x.Id);

 entity.Courses
        .Where(ent => idToDelete.Contains(ent.Id))
        .ToList()
        .ForEach(ent =>
        _contexte.Entry(ent).State = EntityState.Deleted);

This code works fine.

How to perform the same in only one linq instruction?

entity.Courses.RemoveRange(entity.Courses.Where(e => e.Deleted));

Actually, reading your question again, it looks like the list of IDs is in a view model, and possibly your entity model doesn't have the Deleted property. So presumably you need something rather more like what you had:

_contexte.Courses.RemoveRange(
    _context.Courses.Where(c => model.Courses.Where(x => x.Deleted).Select(y => y.Id).Contains(c.Id));

...or more readably:

var idsToDelete = model.Courses.Where(c => c.Deleted).Select(e => e.Id);
var entitiesToDelete = _contexte.Courses.Where(c => idsToDelete.Contains(c.Id));
_contexte.Courses.RemoveRange(entitiesToDelete);

You can use let to declare your idToDelete within the query:

(from ent in in entity.Courses
 let idsToDelete = model.Courses.Where(x => x.Deleted).Select(x => x.Id)
 where idsToDelete.Contains(ent.Id)
 select ent).ToList()
 .ForEach(ent => _contexte.Entry(ent).State = EntityState.Deleted);

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