Part 2:-Learn using Web API with Entity Framework(Creating Domain Models)

Rama Sagar
Posted by in ASP.NET Web API category on for Beginner level | Points: 250 | Views : 6767 red flag

A Model , which represents the underlying, logical structure of data in a MVC application and the high-level class associated with it. This object model does not contain any information about the user interface.

Introduction

This article explain how to create domain Models in the Project which we have created in Part 1

Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

There are three ways to approach Entity Framework:

Database-first: First we start with a database, and Entity Framework does the remaining job.
Model-first: First we start with a visual model, and Entity Framework generates both the database and code.
Code-first: First we start with code, and Entity Framework generates the database.

Here We will use code-first approach, so we start by defining our domain objects as POCOs (plain-old CLR objects). 
With the code-first approach.

Lets start creating POCOs


   Here we create the following POCOs

  1. Book
  2. Order
  3. Order Detail
  • Step 1 : Right click on Models Folder select Add and then select  class

           

  • Step 2 : Add System.ComponentModel.DataAnnotations Namespace and following properties to the Model class
The ScaffoldColumn attribute tells ASP.NET MVC to skip the Id property when generating an editor form. The Required attribute is used to validate the model. It specifies that the Name property must be a non-empty string.
using System.ComponentModel.DataAnnotations;

namespace BooksStore.Models
{
    public class Book
    {
        [ScaffoldColumn(false)]
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        public decimal DealPrice { get; set; }
        public decimal SellingPrice{ get; set; }
    }
}

  
  • Step 3 :Now Lets add  Order class with the following properties
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace BooksStore.Models
{
    public class Order
    {
        public int Id { get; set; }
        [Required]
        public string Customer { get; set; }

        // Navigation property
        public ICollection<OrderDetail> OrderDetails { get; set; }
    }
}

 
  • Step 4 :Now Lets add  OrderDetail class with the following implementation
namespace BooksStore.Models
{
    public class OrderDetail
    {
        public int Id { get; set; }
        public int Quantity { get; set; }
        public int OrderId { get; set; }
        public int BookId { get; set; }

        // Navigation properties
        public Book Book { get; set; }
        public Order Order { get; set; }
    }
}


  • Step 5 :Now Lets configure the Media -Type Formatters

 A media-type formatter is an object that serializes your data when Web API writes the HTTP response body. The built-in formatters support JSON and XML output. By default, both of these formatters serialize all objects by value.

In Solution Explorer, expand the App_Start folder and open the file named WebApiConfig.cs. Add the following code to the WebApiConfig class:


using System.Web.Http;

namespace BooksStore
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //This code sets the JSON formatter to preserve object references, and removes the XML formatter from the pipeline entirely.

            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling =
                Newtonsoft.Json.PreserveReferencesHandling.Objects;

            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }
    }
}



Conclusion

In this article we have learned how to create domain models ..In Next part we will see the Creation of Admin Controller

Reference

http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)