开发者

How to access navigation properties in a ICollection

i have this entity called BlogArticle which has a property called

public virtual ICollection<BlogComment> BlogComments { get; set; }

what开发者_JAVA百科 i wanna do is access those properties of the blogcomments in my view but since it is in a ICollection i cannot itterate through it. (.count() does work.)

Any suggestions on this matter?

cheers.


You can enumerate the collection by using a foreach loop. If you need random access to the elements of the collection you can use the ToList() extension method. That will create a new list containing all the elements of the collection.

foreach (var blogComment in blogArticle.BlogComments) {
   // Access sequentially from first to last.
}

or

var blogComments = blogArticle.BlogComments.ToList();
for (var i = 0; i < blogComments.Count; ++i) {
  var blogComment = blogComments[i]; // Access by index - can be done in any order.
}


ICollection is an interface, so it depends on how you are initializing this object i.e.

ICollection<BlogComment> BlogComments = new List<BlogComment>();

Would allow you to do...

BlogComments.Count;


For future reference being that the question is a bit old... I'm surprised that no one mentioned this before, but if you do not want to do the cast in either the view model or the view itself you could do:

@for(int i = 0; i < model.BlogComments.Count; i++)
{
    @Html.DisplayFor(model => model.BlogComments.ElementAt(i));
}

EDIT: I will add that this is only a useful strategy for displaying data (edited the example to show this), not a useful strategy inside of a form where you want to have the values posted back to your action method when used in HTML helpers like EditorFor. The name property of input is not formed in a way that will allow the model binder to bind these values back to the collection. You would either have to write the name out by hand (not robust) have some sort of intermediary collection type with the index operator like IList that you keep in sync with the ICollection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜