开发者

Getting data out of a model made of multiple tables in a one-to-many relationship

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.


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜