Sql – Linq2SQL related records

asp.net-mvclinq-to-sql

I'm sure this has been answered but I can't find it.

Say I have three tables;

Projects

  • Id <= unique key
  • name

Attributes

  • Id <= unique key
  • Name

ProjectAttributes

  • id <= unique key
  • ProjectId
  • AttributeId

I'm using a dbml file and I have all the associations drawn up within the dbml.

So how in my view, do I itterate through all the Attributes for the project.

I thought;

<% foreach (Project project in Model){%>
    <% foreach (Repository.Attribute attr in project.ProjectAttributes ) { %>

but that clearly doesn't work.

So how, given a project, do I get all the attributes associated to it?

Best Answer

Many to many associations in L2S are always done including the foreign key table, so it should probably be:

<% foreach (Project project in Model){%>
    <% foreach (ProjectAttribute attr in project.ProjectAttributes ) { %>       

And attr.Attribute will then be your needed attribute

Related Topic