I have multiple tables that are all linked back to a central table with foreign keys. I want to be able to create a new record in table 2, but I’m having trouble because I don’t know how to create a new instance of table 2’s record while referencing the ID of the record it will be tied to.
EXAMPLE:
Database: Collection
Table: Collection
Field 1: id
Field 2: name
Table: Book
Field 1: collectionId
Field 2: id
Field 3: name
Now, I don’t want to be able to create a book without setting it’s collectionID, but I can’t figure out how this should be divided in the controllers/views.
Should Book have a controller separate from Collection, or should the Collection controller have a createBook method, separate from it’s own create method?
I want to call the createBook method (from it’s own controller, or the Collection controller) from the Collection Details view.
When I invoke the create method of Book, how do I create a new Book that is instantiated with the collectionId set from the details view of the Collection item that was listed in the details view?
I should point out, I’m using the entity framework for my model, and I’m definitely new to this.
Thanks for any help
Try not to create/separate controllers based on your entity model, create/separate them based on the UI and URL Routes.
I’m guessing you have a View called “CreateBook”, which is (hopefully) bound to a strongly-typed “Book” entity.
When you submit the form, you should have a controller method with
[HttpPost].Then you can do this to submit the book:
or pass it through as a strongly-typed model:
Then you do this:
When you import your model into the EDMX, make sure you tick “Include Foreign Keys in the Model”.
What this does is add the “CollectionID” FK to the Book entity, allowing you to bind to this and have access to this property on each book model.
There is a really good article here on CRUD operations with Strongly Typed ASP.NET MVC Views, should put you on the right track.
HTH.