views:

213

answers:

2

Hi,

I've got a relatively simple question about asp.net MVC models.

I've got a model based on two tables that are linked in a one-to-many relationship.

table AnimalGroup(ID,name)

table AnimalSubGroup(ID,name,AnimalGroupID)

Each AnimalGroup has any number of AnimalSubgroups.

How do I iterate through each AnimalGroup's AnimalSubGroups and get AnimalSubGroup.name (for example)? I'm new to asp.net MVC and have been following various tutorials, but while they're excellent for getting a basic application set up and getting results out of a single table, I'm stuck as to how I'd get results from several tables linked in the same model. I've seen references to ViewModel as a solution, but it seems that ViewModel is more useful for putting data from two unrelated tables into a single View.

Thanks in advance.

A: 

First. Do you have foreign keys defined in your database? If yes, edmx model generator will define all conections. If not, do it right now. When it is done, you can select subgroup name by:

  1. Taking it directly from context:

    context.AnimalSubGroupSet.Where(sg => sg.AnimalGroupID = requestedAnimalGroupID).Select(sg => sg.Name).ToList;

  2. Taking it from AnimalGroup:

    animalGroup.AnimalSubGroups.Select(sg => sg.Name);

This code may need adjustments, but they shouldn't be complicated.

LukLed
Neither of those seems to work: context doesn't even exist, and the second one works but returns an empty list (and my database is not empty). I'm defining private AnimalGroupEntities _animalGroupDataModel = new AnimalGroupEntities(), then passing it to the view as return View(_animalGroupDataModel.AnimalGroup.ToList());In the view, I have var groups = item.AnimalGroupSubcategory.Select(sg => sg.name); and then I iterate over the entries of groups, which is where things break down.I apologize for the messiness of the comment - is there a way to add line breaks?
sslepian
@sslepian: If you want to use the second, you have to call `animalGroup.AnimalSubGroups.Load()` first. And for the first `context = _animalGroupDataModel`.
LukLed
Oh wow, that solved it. Thanks so much!On a related note, is there a good tutorial for the ado.net entity framework that you'd recommend? None of the ones I found covered this, and a lot of them use LINQ which isn't really useful to me.
sslepian
@sslepian: I would strongly suggest you to buy a book: http://stackoverflow.com/questions/258840/how-should-i-get-started-learning-about-ado-net-entity-framework
LukLed
A: 

Perhaps you should take a look at LINQ's SelectMany query operator. This sub-iterates over one-to-many data table relationships. Note that you can chain SelectMany calls:

var mymanyselections = datacontext.parenttable.SelectMany(l=>l.Name).SelectMany(m=>m.Name);

This assumes that you have foreign key relationships in your data tables.

aastle