ASP.NET MVC 3 How to handle one-to-many associations
I have a domain object Article
which can have multiple Shapes
whereas a Type is a child of the article and cannot be associated with any other article (one-to-many).
The association is modelled as a collection:
class Article
{
int ID;
string Name;
ICollection<Shape> Shapes;
}
If I scaffold this entity, the generated controllers and views seem to only support the simple datatype fields such as Name
. The views contain an input field for Name
. If I post the filled-in form, the MVC framework creates an Article
object and sets its Name
property to the given value. This object is passed to the controller method开发者_开发百科.
How can I add support for one-to-many associations such as Shapes? I desire the following behavior of the Article
view within the browser:
- Child entities are listed in a table.
- I can add a new child entity to the table, by which it is created and associated in the database.
- I can edit the individual properties of an existing entry.
Ideally, I hope to be able to retrieve all those changes in the controller method as follows:
public ActionResult Create(Article article)
{
var types = article.Types;
Where types
is supposed to contain all child types. The entities that already existed before should have the right id. The properties however should reflect what the user set in the browser (just as it does for the Article
object).
Entities that have been newly added won't have an ID and won't exist in the database yet, it is my job as a programmer to retrieve the objects from the collection and store them in the database.
My Question:
Is there any support in MVC 3 for one-to-many relationships? Alternatively, are there any best practices how to implement it on your own?
Please note that many resources using the term "one-to-many" that I found on the web unfortunately actually speak of one-to-one or many-to-one relationships, that is, although you can pick from a list of many entities, you only select and associate a single one.
精彩评论