ASP.net MVC Linq-To-SQL Many-To-Many Field Binding
Posted
by user336858
on Stack Overflow
See other posts from Stack Overflow
or by user336858
Published on 2010-06-01T20:21:30Z
Indexed on
2010/06/03
3:04 UTC
Read the original article
Hit count: 254
Hi there,
The short version of this question is "Is there a way to gracefully handle database insertion for an object that has a many-to-many field that has been set up in a partial class?" Apologies if it's been asked before.
Example
Suppose I have a typical MVC setup with the tables:
- Posts {PostID, ...}
- Categories {CategoryID, ...}
A post can have more than one category, and a category can identify more than one post. Thus suppose further that I need an extra table:
- PostCategories {PostID, CategoryID, ...}
This handles the many-to-many relationship between posts and categories. As far as I know, there's no way to do this in Linq-to-SQL right now so I have to shoehorn it in by adding a partial Post class to the project to add that functionality. Something like:
public partial class Post
{
public IEnumerable<Category> Categories{ get { ... } set { ... } }
}
So I can now create a "Create" view that automatically populates a "Categories" UI item. This is where the trouble starts.
So here's my question:
How do you get automatic object model binding to work cleanly with an object that has a many-to-many relationship to control? The workaround that makes many-to-many relationships possible relies on the Post object having a PostID in order to be associated with CategoryID(s), which is only issued after the Post object has been submitted for validation and insertion.
Bit of a Catch22 here. Any terminology, links, or tips you can provide would be tremendously helpful!
© Stack Overflow or respective owner