How do I foreach through my dbcontext entities in EF 4.1?

Benjamin picture Benjamin · Jun 13, 2011 · Viewed 20k times · Source

I'm using ASP.NET Entity Framework 4.1 MVC 3 (C#)

I want to foreach through all the entities in my DbContext. I need to be able to dynamically refer to my entities in order to make dynamic views.

I have read Lerman's book, two MVC (2 & 3) books, msdn, asp.net, etc. Maybe I am just missing something?

It seems like you might have to use ObjectContext to get to the entities. If that is the right way, I sure can't figure out how to do it. Please help. Thank you.

Answer

GisMofx picture GisMofx · Oct 17, 2011

you can also do this(for example):

foreach (var dbItem in dbContext.Items)
{
    //do what you want inside the loop with the dbItem
    sList.Add(new SelectListItem() {Text = dbItem.ItemName, Value = dbItem.ItemTag});
}