Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
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)<br />        {<br />            using (AppEntities context = new AppEntities())<br />            {<br />                var reservations = from u in context.Users.Include("Reservations")<br />                                   where u.UserId == userId<br />                                   select u.Reservations;<br /><br />                foreach (Reservation res in reservations.ToList())<br />                {<br />                    context.DeleteObject(res);<br />                }<br /><br />                context.SaveChanges();<br />            }<br />        }


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<reservation>" with ToList(). But normally I don't user a navigation property, so maybe they behave different than "normal" results?

Any ideas?

Shi
Posted

1 solution

Here's your problem:
var reservations = from u in context.Users.Include("Reservations")<br />                   where u.UserId == userId<br />                   select u.Reservations;

The Reservations members in your User object is actually a collection of entities; what your select clause actually creates is an IQueryable<EntitySet<Reservation>> collection, not an IQueryable<Reservation> like you would expect.

If you're trying to aggregate/concatenate the Reservations collections from multiple User objects, you need to look into using LINQ's Enumerable.SelectMany[^] extension method.
 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900