In an MVC view, I'm looking for a way to determine if a parent entity's collection of child entities is empty, so I can decide if I need to call a RenderPartial() or not.
For a one-to-one I've been using the following:
<% if (Model.Book.GenreReference.EntityKey != null) %>
{.....}
but I'm unsure how to do it in a one-to-many scenario, or if it can even be done without the use of Include() or Load().开发者_运维问答
Write a view model:
public class BookPresentation
{
public Guid Id { get; set; }
public string Title { get; set; }
public bool HasOrders { get; set; }
public int ReviewCount { get; set; }
}
Then project onto it:
var model = from b in db.Books
where b.Id == id
select new BookPresentation
{
Id = b.Id,
Title = b.Title,
HasOrders = b.Orders.Any(),
ReviewCount = b.Reviews.Count()
};
First of all, you really should have all the data loaded from the DB by the time your model is passed on to the view. Given that, you should have used Include
in your query (or Load
afterwards) to grab the collection of children in the controller action.
In the view you then do a usual check (something along the lines of):
<% if (Model.Book.Children != null && Model.Book.Children.Any()) %>
(Instead of Children
you actually use the navigation property you have - could be Authors
for example).
精彩评论