Many:Many

Feb 7, 2011 at 1:45 AM
Edited Feb 7, 2011 at 2:06 AM

How would I go about creating a Many:Many Relationship using the Scaffolding?

Examples:

ContactGroup can have Many Customers; and Customers can belong to Many ContactGroups

Using Tables: [Customer], [CustomerContactGroup], [ContactGroup],

While having another Many:Many Relationship using tables: [Staff], [StaffContactGroup], [ContactGroup]

Where [ContactGroup] is the Same Table in both.

Or did I just completely mess-up the Normalization of the database structure to begin with and the business rules don't make any sense?

[Edit: Just found this: http://mikeyhogarth.wordpress.com/2011/02/05/implementing-many-to-many-relationships-in-mvc3/   - That is probally a better example of what trying to ask how to do with Scaffolding.]

Feb 28, 2011 at 12:06 PM

I don't think MvcScaffold supports many to many in a sexy way like it does with one-to-many

Hopefully Steven Sanderson has it in store for us, or someone from the community can patch it up

Mar 1, 2011 at 5:45 AM

 

 While a standard practice would be to create in intermediate table [CustomerContactGroup] that used a composite key made up from the foreign keys from your [Customer] and [ContactGroup] tables, I found that I could scaffold the relationship using a separate single column key (excluding the foreign keys). While the column names get a little verbose here, the class itself should be clear. I'd bet some will argue it's less efficient but the productivity gained by scaffolding multiple classes over and over is certainly worth the effort. In any case, the class below should work to build a table to manage the relationship.

 I must add however, that our intent is to use scaffolding while building out the design, then optimize the database and recreate the interface using EF to generate from that database. Sorry, old SQL guy - some things like cascades are better handled via SQL. That said, I remain utterly impressed by this work and find it a huge productivity gain.

namespace YourNamespace.Models

{

    public class CustomerContactGroup

    {

        public int CustomerContactGroupId{ getset; }

 

        public int CustomerId { getset; }

        public virtual Customer Customer { getset; }

 

        public int ContactGroupId { getset; }

        public virtual ContactGroup ContactGroup { getset; }

 

        public int? OtherFields { getset; }

        public string AsRequired { getset; }

 

    }

}