删除对象列表 [英] Deleting a list of objects

查看:162
本文介绍了删除对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我尝试删除对象列表(给定用户的所有保留).

我在迭代列表时遇到问题,这是我的问题到目前为止的代码:

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 />        }



问题出在"foreach(保留中的保留资源)"部分..它引发异常,告诉我它无法从一种类型转换为另一种类型. .但我不明白,通常我可以直接投射到例如"IList<预订>"与ToList().但是通常我不使用导航属性,所以也许它们的行为不同于正常"结果?

有什么想法吗?

Shi



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

推荐答案

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


User对象中的Reservations成员实际上是实体的集合;您的select子句实际创建的是一个IQueryable<EntitySet<Reservation>>集合,而不是您期望的IQueryable<Reservation>.

如果您试图从多个User集合/连接Reservations集合>对象,您需要研究使用LINQ的 Enumerable.SelectMany [^ ]扩展方法.


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.


这篇关于删除对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆