Tuesday, October 29, 2013

How to create Web API using code first Entity Framework 5.0

How to create Web API using code first Entity Framework 5.0

1) Create ASP.NET MVC 4 application

2) Select Web API Project template

3) Create a Customer class

         public class Customer
    {
        [Key]
        public int custId { get; set; }
        public String Name { get; set; }
        public DateTime DOJ { get; set; }
        public String szEmailID { get; set; }
        public string Mobile { get; set; }
    }
     

4) Create CustomerModel class which is Derived from DBContext

 public class CustomerModel:DbContext
    {
        public CustomerModel() : base("CustDB") { }

        protected override void OnModelCreating(DbModelBuilder mb)
        {
           // mb.Entity<Customer>().ToTable("Customers");
        }


        public DbSet<Customer> customers { get; set; }
    }

   CustDB is a Connection String Specified in Web.config
 <add name="CustDB"
providerName="System.Data.SqlClient" 
connectionString="Server=C4968397007;Trusted_connection=yes;database=mydb;"/>

5) Build the Project


6) Create a Controller Class Select "API controller with read/write operations using Entity Frame "
      Name it as "CustomerController"
      In this 
        select DataContext as CustomerModel
                  Model Class as Customer

7)  That;s it

8) Just run the Web API class in Browser

    http://localhost:port/api/Customer


U will get Empty JSON/XML data.



How to Insert,UPDATE,DELETE on Web API 

pls see below articles

No comments:

Post a Comment