A ‘Many To Many’ field template for Dynamic Data
Update: the Many to Many template is now part of the default Dynamic Data project template (when using Entity Framework), so you should not need to download this template separately unless you're on 3.5SP1
Unlike Linq To Sql, Entity Framework directly supports Many to Many relationships. I’ll first describe what this support means.
In the Northwind sample database, you have Employees, Territories and EmployeeTerritories tables. EmployeeTerritories is a ‘junction’ table which has only two columns: an EmployeeID and a TerritoryID, which creates a Many to Many relationship between Employees and Territories.
When using Linq To Sql, all three tables get mapped in your model, and you need to manually deal with the EmployeeTerritories junction table. But when using Entity Framework, the EmployeeTerritories junction table is not part of your model. Instead, your Employee entity class has a ‘Territories’ navigation property, and conversely your Territory entity class has an ‘Employees’ navigation property. What Entity Framework does under the cover to make all this work is pretty amazing!
Unfortunately, in ASP.NET Dynamic Data’s initial release (as part of Framework 3.5 SP1), we didn’t have time to add proper support for such Many to Many relationships, and in fact it behaves in a pretty broken way when it encounters them.
The good news is that it is possible to write a field template that adds great support for this, and that is exactly what this blog post is about. I should note that a couple of our users have written such field templates before (in particular, see this post). In fact, that’s what got me going to write one! :)
One difference is that I set mine out to be completely generic, in the sense that it doesn’t assume any specific database or table. e.g. it works for Northwind’s Employees/Territories (which my sample includes), but works just as well for any other database that uses Many to Many relationships.
In read-only mode, it shows you a list of links to the related entities. e.g. when looking at a Territory, you’ll see links to each of the Employees that work there.
In edit mode, it gets more interesting: it displays a list of checkboxes, one for each Employee in the database. Then, whether the Employee works in this territory is determined by whether the checkbox is checked. Pretty much what you’d expect!
I won’t go into great details about how it works here, but if you are interested, I encourage you to download the sample and look at the code, which I commented pretty well. The key things to look at are:
- The field templates ManyToMany.ascx (used for read-only) and ManyToMany_Edit.ascx (used for Edit).
- The AutoFieldGenerator, which automatically uses those field templates for Many to Many relationships.
Enjoy, and let me know if you have feedback on this.