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]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值