Getting Started - Web API


ASP.NET Web API

    • After created data model in Library project - From solution explorer right click on your project  , select Add, then select new Scaffolded Item , select Web API Controller - Empty, In the Add Controller dialog name the controller BooksController (Web API controllers inherit the ApiController class that handles HTTP requests).
    • Add new folder named ViewModels , In ViewModels folder add new class Named BooksVm and class named AuthorVm Write the following :
    "You can consider using of viewModels classes as data transfer object(DTO)
    this is to avoid circular references becouese of navagtion property in Author class
    also you may need to hide or add some new property. see also"

    //BookVm.cs


    namespace Library.ViewModels
    {
        public class BookVm
        {
            public int BookId { get; set; }
            public string BookName { get; set; }
            public int AuthorId { get; set; }
            public string AuthorName { get; set; }
        }

    }

    //AuthorVm.cs


    namespace Library.ViewModels
    {
        public class AuthorVm
        {
            public int AuthorId{ get; set; }
            public string AuthorName { get; set; }
            public int BookCount { get; set; }
        }

    }

    • Back to Controllers ,ِRight click in Controllers folder and  Add new Web API Controller - Empty, In the Add Controller dialog name the controller AuthorsController
    • Add the following methods(These methods implement GET , Post request) to BooksController.cs and AuthorsController.cs
    //BooksController.cs


    namespace Library.Controllers
    {
        [Route("api/books")]
        public class BooksController : ApiController
        {
            LibraryDbContext db = new LibraryDbContext();
            public IQueryable<BookVm> GetBooks()
            {
                var books = from book in db.Books
                           select new BookVm
                           {
                               BookId = book.BookId,
                               BookName = book.BookName,
                               AuthorId = book.AuthorId,
                               AuthorName = book.Author.AuthorName
                           };
                return books;
            }
        }
    }

    //AuthorController.cs


    namespace Library.Controllers
    {
        [Route("api/authors")]
        public class AuthorsController : ApiController
        {
            LibraryDbContext db = new LibraryDbContext();
            public IQueryable<AuthorVm> GetBooks()
            {
                var authors = from author in db.Authors
                           select new AuthorVm
                           {
                               AuthorId = author.AuthorId,
                               AuthorName = author.AuthorName,
                               BookCount = author.Books.Count()
                           };
                return authors;
            }
        }
    }


    • Now we have "Get method" in each controller ,  Run your project to test get request e.g. http://localhost:xxxx/api/books or http://localhost:xxxx/api/authors .


    • to configure retrieved formatter for the JSON data to retrieve Json "Camel case"  , In the App_Start folder open WebApiConfig.cs And add the following code to Register method :
    //WebApiConfig.cs

    var json = config.Formatters.JsonFormatter;

                json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

    - link to project in github.

    Getting Started - Entity Framework Code First


    Entity Framework Code First

     - This article is Part of a series :


    • open visual studio and Create a new web application named Library
    • Select Empty template and click OK
    • From the Tools menu click NuGet Package Manager and then click Package Manager Console. In the Package Manager Console write the following command: 
    PM> Install-Package EntityFramework

    - Create the Data Model

    • add new folder named Models then Create 2 classes named Author.cs  and Book.cs and write the following Code : 
    //Author.cs


    using System;
    using System.Collections.Generic;

    namespace Library.Models
    {
        public class Author
        {
            public int AuthorId { get; set; }
            public string AuthorName { get; set; }
            public virtual ICollection<Book> Books { get; set; }
        }

    }

       
    //Book.cs



    namespace Library.Models
    {
        public class Book
        {
            public int BookId { get; set; }
            public string BookName { get; set; }
            public int AuthorId { get; set; }
            public virtual Author Author { get; set; }
        }

    }

    - Create the Database Context

    • Create new folder named DataLayer and add new class named LibraryDbContext.cs and write the following Code : 
    //LibraryDbContext.cs


    using Library.Models;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;

    namespace Library.DataLayer
    {
        public class LibraryDbContext : DbContext
        {
            public LibraryDbContext()
                : base("DefaultConnection")
            {

            }


            public DbSet<Book> Books { get; set; }
            public DbSet<Author> Authors { get; set; }


            public static LibraryDbContext Create()
            {
                return new LibraryDbContext();
            }
        }

    }

    • From the Tools menu click NuGet Package Manager and then click Package Manager Console. In the Package Manager Console write the following command:
    PM> Enable-Migrations
    • After enabling migrations has done add to seed method in Configuration class follwing :

    //Configuration.cs


    protected override void Seed(Library.DataLayer.LibraryDbContext context)
            {
                context.Authors.AddOrUpdate(a => a.AuthorName, new Author { AuthorName = "Stephen Hawking" });
                context.Authors.AddOrUpdate(a => a.AuthorName, new Author { AuthorName = "Elisabeth Kübler-Ross" });
                context.Authors.AddOrUpdate(a => a.AuthorName, new Author { AuthorName = "Tony Crilly" });
                context.SaveChanges();
                context.Books.AddOrUpdate(a => a.BookName, new Book { BookName = "A brief history of time" , AuthorId = context.Authors.Single(a => a.AuthorName == "Stephen Hawking").AuthorId });
                context.Books.AddOrUpdate(a => a.BookName, new Book { BookName = "Death: The Final Stage of Growth"  , AuthorId = context.Authors.Single(a => a.AuthorName == "Elisabeth Kübler-Ross").AuthorId });
                context.Books.AddOrUpdate(a => a.BookName, new Book { BookName = "50 Mathematical Ideas You Really Need to Know" , AuthorId = context.Authors.Single(a => a.AuthorName == "Tony Crilly").AuthorId });
                context.Books.AddOrUpdate(a => a.BookName, new Book { BookName = "The Grand Design" , AuthorId = context.Authors.Single(a => a.AuthorName == "Stephen Hawking").AuthorId });

            }


    PM> Add-Migration initial-libraryDbContext
    • In the generated  migration class turn cascadeDelete to false 
    //initiallibraryDbContext

        public partial class initiallibraryDbContext : DbMigration
        {
            public override void Up()
            {
                CreateTable(
                    "dbo.Authors",
                    c => new
                        {
                            AuthorId = c.Int(nullable: false, identity: true),
                            AuthorName = c.String(),
                        })
                    .PrimaryKey(t => t.AuthorId);
               
                CreateTable(
                    "dbo.Books",
                    c => new
                        {
                            BookId = c.Int(nullable: false, identity: true),
                            BookName = c.String(),
                            AuthorId = c.Int(nullable: false),
                        })
                    .PrimaryKey(t => t.BookId)
                    .ForeignKey("dbo.Authors", t => t.AuthorId, cascadeDelete: false)
                    .Index(t => t.AuthorId);
               
            }
           
            public override void Down()
            {
                DropForeignKey("dbo.Books", "AuthorId", "dbo.Authors");
                DropIndex("dbo.Books", new[] { "AuthorId" });
                DropTable("dbo.Books");
                DropTable("dbo.Authors");
            }
        }


    • Right click on your project, select Add, then Add ASP.Net Folder and choose the App_Data folder
    PM> Update-Database -Verbose

    • That is all! now we have our database working and you can explorer it , Next article will be in how to create ASP.NET RESTful APIs (web api) .
    - link to project in github.