好的,我有一个强类型的客户“详细信息” View ,它采用客户对象模型。
我正在使用 LINQ to SQL,每个客户都可以拥有多个( parking 位)。
这是数据库中的 FK 关系,因此我的 LINQ 生成的客户模型具有“Spaces”集合。太棒了!
这是来 self 的 CustomerRepository 的代码片段,我在其中迭代客户的 parking 位以删除所有付款、车位,最后删除客户:
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);
}
一切都按预期进行!
现在,在我的“详细信息” View 中,我想用客户空间填充表格:
<% foreach (var s in Model.Spaces)
{ %>
<tr>
<td><%: s.ID %></td>
<td><%: s.InstallDate %></td>
<td><%: s.SpaceType %></td>
<td><%: s.Meter %></td>
</tr>
<% } %>
我收到以下错误:
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'
最后,如果我将这段代码添加到我的 Customer 部分类中,并在 View 中使用 foreach 来迭代 ParkingSpaces,一切都会按预期工作:
public IEnumerable<Space> ParkingSpaces
{
get
{
return Spaces.AsEnumerable();
}
}
这里的问题是我不想重复自己。我还认为我可以使用 ViewModel 将 Spaces 集合传递给 View,但是 LINQ 已经在 Customer 模型上推断并创建了 Spaces 属性,因此我认为仅使用它是最干净的。
我遗漏了一些简单的东西,还是我处理方法不正确?
谢谢!
最佳答案
抱歉,如果我回答这个问题有点晚了,但解决问题的正确方法是向 web.config 文件添加程序集引用,以便 View 可以访问 GetEnumerator() 方法。您可以使用页面编译错误中提供的程序集引用字符串来执行此操作。 例如
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
关于linq-to-sql - ASP.NET MVC/LINQ : What's the proper way to iterate through a Linq. View 中的实体集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2710405/