foreach in entityset

文章讨论了如何正确地在ASP.NET MVC视图中遍历LINQ EntitySet,提供了解决错误的方法,并解释了使用EntitySet与视图交互的最佳实践。
QS:
OK so I have a strongly-typed Customer "Details" view that takes a Customer object Model.

I am using LINQ to SQL and every Customer can have multiple (parking) Spaces.

This is a FK relationship in the database so my LINQ-generated Customer model has a "Spaces" collection. Great!

Here is a code snippet from my CustomerRepository where I iterate through the Customer's parking spaces to delete all payments, spaces and then finally the customer:

public void Delete(Customer customer)
{
foreach (Space s in customer.Spaces)
db.Payments.DeleteAllOnSubmit(s.Payments);
db.Spaces.DeleteAllOnSubmit(customer.Spaces);
db.Customers.DeleteOnSubmit(customer);
}
Everything works as expected!

Now in my "Details" view I want to populate a table with the Customer's Spaces:

<% foreach (var s in Model.Spaces)
{ %>
<tr>
<td><%: s.ID %></td>
<td><%: s.InstallDate %></td>
<td><%: s.SpaceType %></td>
<td><%: s.Meter %></td>
</tr>
<% } %>
I get the following error:

foreach statement cannot operate on variables of type 'System.Data.Linq.EntitySet' because 'System.Data.Linq.EntitySet' does not contain a public definition for 'GetEnumerator'

Finally, if I add this bit of code to my Customer partial class and use the foreach in the view to iterate through ParkingSpaces everything works as expected:

public IEnumerable<Space> ParkingSpaces
{
get
{
return Spaces.AsEnumerable();
}
}
The problem here is that I don't want to repeat myself. I was also thinking that I could use a ViewModel to pass a Spaces collection to the View, however LINQ already infers and creates the Spaces property on the Customer model so I think it would be cleanest to just use that.

I am missing something simple or am I approaching this incorrectly?

Thanks!
ANS:Sorry if Im a bit late answering this but the correct method of solving your problem is to add an assembly reference to your web.config file so that the view can access the GetEnumerator() method. You can do this using the assembly reference string provided in the page compliation error. eg

[color=red]<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>[/color]

原文:[url]http://stackoverflow.com/questions/2710405/asp-net-mvc-linq-whats-the-proper-way-to-iterate-through-a-linq-entityset-in-a[/url]
<think>好的,用户想了解foreach在列表中的用法。首先我需要整理不同编程语言中的foreach循环实现,因为不同语言的语法可能不同。根据提供的引用资料,CMake、PHP、Java都有相关的示例。 先看引用[1]中的CMake例子,CMake的foreach命令用于遍历列表中的项,支持多种格式,包括直接遍历列表、范围生成和zip多列表。需要解释每种格式的用法,比如基本结构、RANGE和IN的用法。 接下来是引用[2]提到的PHP数组遍历,PHP中的foreach可以处理数组和对象,需要比较foreach与其他循环方式(如for、each-while)的不同,强调其适用场景和优势。 引用[3]和[4]是Java的例子,使用forEach方法和Lambda表达式。Java 8引入了forEach方法,可以结合Lambda简化遍历操作,比如用箭头函数处理每个元素。此外,Predicate接口的例子展示了如何在遍历时进行条件判断。 用户的问题可能涉及不同语言,所以需要分语言说明。要确保每个示例的语法正确,比如Java中的List声明和Lambda表达式,CMake中的循环结构。同时,注意用户可能希望了解基本用法、语法结构以及实际应用场景。 还需要生成相关问题,可能涉及性能比较、不同循环方式的优缺点、如何结合条件过滤等。确保回答结构清晰,分点说明,并引用提供的资料作为支持。</think>关于`foreach`在列表中的用法,以下是分语言的具体实现解析和示例: ### 一、CMake中的`foreach` 在CMake脚本中,`foreach`用于遍历列表项,支持四种语法格式: 1. **基础遍历**:直接处理分号/空格分隔的列表 ```cmake set(items "apple;banana;cherry") foreach(item ${items}) message("Fruit: ${item}") endforeach() ``` 输出:依次打印`apple`、`banana`、`cherry`[^1] 2. **数值范围遍历**:通过`RANGE`生成连续整数 ```cmake foreach(i RANGE 1 3) # 遍历1,2,3 message("Number: ${i}") endforeach() ``` 3. **多列表联合遍历**:使用`IN`合并多个列表 ```cmake set(list1 "a;b") set(list2 "1;2") foreach(elem IN LISTS list1 list2) message("Element: ${elem}") # 输出a,b,1,2 endforeach() ``` 4. **多列表并行遍历**:`ZIP_LISTS`实现同步遍历 ```cmake set(names "Tom;Jerry") set(ages "25;30") foreach(name age IN ZIP_LISTS names ages) message("${name} is ${age} years old") # Tom/25, Jerry/30 endforeach() ``` ### 二、PHP中的`foreach` PHP的`foreach`专门为数组遍历设计,支持键值对提取: ```php $colors = ["red", "green", "blue"]; foreach ($colors as $index => $value) { echo "Index: $index, Value: $value\n"; } ``` 优势场景: - 无需初始化计数器 - 自动处理关联数组 - 直接修改原数组元素(通过引用`&$value`) 与其他遍历方式对比: | 方法 | 适用场景 | 性能特点 | |-----------------|------------------------|---------------| | `foreach` | 数组全遍历 | 内存占用低 | | `for` | 需要索引控制时 | 需预计算长度 | | `each+while` | 兼容老版本PHP | 效率较低 | ### 三、Java中的`forEach` Java 8+ 提供`forEach`方法结合Lambda表达式: ```java List<String> list = Arrays.asList("A","B","C"); // Lambda简写 list.forEach(item -> System.out.println(item)); // 方法引用 list.forEach(System.out::println); ``` 带条件过滤的遍历(结合Predicate): ```java list.stream() .filter(s -> s.startsWith("A")) .forEach(System.out::println); // 输出"A" ``` 这种函数式编程风格使代码更简洁[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值