CodeCloudy

Azure | .Net | JQuery | Javascript | Umbraco

Asp.net Web API 102 – Scaffolding

on March 19, 2014

In the previous blog we discussed the Basics of Web API and try to understand the default code. Now we will try to create our custom Web API using a Case Study.

Case study:

We will build our own requirement.

  • We have a Public Product Catalog
  • Any organization or an individual can publish their products here
  • We will add more requirements when we move forward…

Step 1: Create a Model “Product”


(Note: I have put full namespaces so you can better understand where it came from.)

I have added some data annotations to the properties.

  • ID will be the Key property.
  • Name property is marked as required.
  • And the maximum length of the Description will be 500 characters.

Now let’s use Scaffolding to create the Controller using the Model “Product”.

Step 2: Select Scaffolding for Web API 2 with Entity Framework

Right Click Controller Folder à Add à Select “New Scaffolded Item”


Choose the following option in the Web API category:


Step 3: Populate Controller Details for Scaffolding

  • Give a Controller Name
  • You have the option to create Controllers with Asynchronous Controller Actions or without.
  • Select the Model Class “Product”
  • Create a New Data Context to work with Databases.


Error 1:

When scaffolding the controller from the Model following error may appear:

“There was an error generating ‘WebAPI1.Models.DBContext. Try rebuilding your project.”

Rebuilding the project would solve this error.

Error 2:

If the Product class doesn’t have a key property, when scaffolding following error may appear. Example: if ID property doesn’t have the Data Annotation Key.


Note: Make sure you rebuild the project after you add the Key property. Also rebuild after any changes in the Model, before Scaffolding.

Now you have Created the your custom API Controller “ProductController”.

In the next blog we will see the differences of Actions with and without Asynchronous behavior.


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: