Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC/LINQ: What's the proper way to iterate through a Linq.EntitySet in a View?
    primarykey
    data
    text
    <p>OK so I have a strongly-typed Customer "Details" view that takes a Customer object Model.</p> <p>I am using LINQ to SQL and every Customer can have multiple (parking) Spaces.</p> <p>This is a FK relationship in the database so my LINQ-generated Customer model has a "Spaces" collection. Great!</p> <p>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:</p> <pre><code>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); } </code></pre> <p>Everything works as expected!</p> <p>Now in my "Details" view I want to populate a table with the Customer's Spaces:</p> <pre><code>&lt;% foreach (var s in Model.Spaces) { %&gt; &lt;tr&gt; &lt;td&gt;&lt;%: s.ID %&gt;&lt;/td&gt; &lt;td&gt;&lt;%: s.InstallDate %&gt;&lt;/td&gt; &lt;td&gt;&lt;%: s.SpaceType %&gt;&lt;/td&gt; &lt;td&gt;&lt;%: s.Meter %&gt;&lt;/td&gt; &lt;/tr&gt; &lt;% } %&gt; </code></pre> <p>I get the following error:</p> <blockquote> <p>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'</p> </blockquote> <p>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:</p> <pre><code>public IEnumerable&lt;Space&gt; ParkingSpaces { get { return Spaces.AsEnumerable(); } } </code></pre> <p>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.</p> <p>I am missing something simple or am I approaching this incorrectly?</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload