Deleting a list of objects
-
Hi, I try to delete a list of objects (all reservations for a given user). I've got problems with iterating the list, here's my code so far:
public void DeleteReservationsByUserId(int userId) { using (AppEntities context = new AppEntities()) { var reservations = from u in context.Users.Include("Reservations") where u.UserId == userId select u.Reservations; foreach (Reservation res in reservations.ToList()) { context.DeleteObject(res); } context.SaveChanges(); } }
The problem lies in the "foreach (Reservation res in reservations)" part.. it throws an exception, tell me that it cannot convert from one type to another.. but I don't understand, normally I can directly cast to eg. "IList" with ToList(). But normally I don't user a navigation property, so maybe they behave different than "normal" results? Any ideas? Shi
-
Hi, I try to delete a list of objects (all reservations for a given user). I've got problems with iterating the list, here's my code so far:
public void DeleteReservationsByUserId(int userId) { using (AppEntities context = new AppEntities()) { var reservations = from u in context.Users.Include("Reservations") where u.UserId == userId select u.Reservations; foreach (Reservation res in reservations.ToList()) { context.DeleteObject(res); } context.SaveChanges(); } }
The problem lies in the "foreach (Reservation res in reservations)" part.. it throws an exception, tell me that it cannot convert from one type to another.. but I don't understand, normally I can directly cast to eg. "IList" with ToList(). But normally I don't user a navigation property, so maybe they behave different than "normal" results? Any ideas? Shi
Here's your problem:
var reservations = from u in context.Users.Include("Reservations")
where u.UserId == userId
select u.Reservations;The
Reservations
members in yourUser
object is actually a collection of entities; what yourselect
clause actually creates is anIQueryable<EntitySet<Reservation>>
collection, not anIQueryable<Reservation>
like you would expect. If you're trying to aggregate/concatenate theReservations
collections from multipleUser
objects, you need to look into using LINQ'sEnumerable.SelectMany
[^] extension method. -
Here's your problem:
var reservations = from u in context.Users.Include("Reservations")
where u.UserId == userId
select u.Reservations;The
Reservations
members in yourUser
object is actually a collection of entities; what yourselect
clause actually creates is anIQueryable<EntitySet<Reservation>>
collection, not anIQueryable<Reservation>
like you would expect. If you're trying to aggregate/concatenate theReservations
collections from multipleUser
objects, you need to look into using LINQ'sEnumerable.SelectMany
[^] extension method.