Thursday, January 21, 2016

Web API From Code (Entity frameworkk code first model)

If you going to target mobile based applications to the small business you need to have API/web service on the hand.

Today we are going to develop Web API within few minutes.

Im using entity framework code first model approach here. (You can use same approach with Asp.NET web sites too) 

Advantages of Code first Model
  • All handle in the code. Full control with the code
  • No need to worry about the database

Here is the scenario today im working.

There is DVD rental store. Which each user can get one or more movie dvd's . 
















1. Create Asp.NET web API project
2. Then Add the following classes to it in model

TransactionId is auto increment 

/// <summary>
/// User Db Model 
/// </summary>
public class User
{
    public Guid UserId { getset; }
    public string UserName { getset; }
    public string NIC { getset; }
    public DateTime BirthDay { getset; }
 
    //One user may have multiple transactions
    public virtual ICollection<Transaction> Transactions { getset; }
}

/// <summary>
/// Video Db Model
/// </summary>
public class Video
{
    public Guid VideoId { getset; }
    public string VideoName { getset; }
    public string Publisher { getset; }
 
    //One video may have multiple transactions 
    public virtual ICollection<Transaction> Transactions { getset; }
}

/// <summary>
/// Transaction db model
/// </summary>
public class Transaction
{
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public int TransactionId { getset; }
    public Guid UserId { getset; }
    public Guid VideoId { getset; }
    public DateTime ReserveDate { getset; }
    public DateTime ReturnDate { getset; }
 
    //Add forign key 
    public virtual Video Video { getset; }
    public virtual User User { getset; }
} 

3. Install Entity Framework
4. Create Db Context file (RentalContext)
/// <summary>
/// Database context 
/// </summary>
public class RentalContext:DbContext
{
    public RentalContext():base("RentalContext")
    {
 
    }
 
    /******************Database tables ******************/
    public DbSet<User> UserSet { getset; }
    public DbSet<Video> VideoSet { getset; }
    public DbSet<Transaction> TranactionSet { getset; }
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         base.OnModelCreating(modelBuilder);
    }
}

5. Then create Db initialize to change database when any changes happen with model
***With few sample data

public class RentalInitilizer : DropCreateDatabaseIfModelChanges<RentalContext>
{
    /// <summary>
    /// Add sampe data to the database 
    /// </summary>
    /// <param name="context"></param>
    protected override void Seed(RentalContext context)
    {
        List<User> Users = new List<User>()
        {
            new User(){BirthDay=Convert.ToDateTime("1990-05-03"),NIC="90563247855V",UserId=new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),UserName="Dummy User1"},
            new User(){BirthDay=Convert.ToDateTime("1990-05-03"),NIC="90563247855V",UserId=new Guid("93d92550-eefb-4b08-aab9-aa0cf8f3309f"),UserName="Dummy User2"},
            new User(){BirthDay=Convert.ToDateTime("1990-05-03"),NIC="90563247855V",UserId=new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),UserName="Dummy User3"}
 
        };
 
        Users.ForEach(x => context.UserSet.Add(x));
 
        List<Video> Videos = new List<Video>()
        {
            new Video(){Publisher="Publisger 1",VideoId=new Guid("4fb4912c-6f7d-4d34-8fd0-9ec641ae328d"), VideoName="Video 1"},
            new Video(){Publisher="Publisger 2",VideoId=new Guid("bcfc276a-8c41-40ad-bb7b-05731dbfcce5"), VideoName="Video 2"},
            new Video(){Publisher="Publisger 3",VideoId=new Guid("6a95ce93-6b9d-4d29-9bb0-fb69e2bb53bb"), VideoName="Video 6"}
 
        };
        Videos.ForEach(x => context.VideoSet.Add(x));
 
        List<Transaction> Transactions = new List<Transaction>()
        {
            new Transaction(){ReserveDate=DateTime.Now,ReturnDate=DateTime.Now.AddDays(5),UserId= new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),VideoId=new Guid("6a95ce93-6b9d-4d29-9bb0-fb69e2bb53bb")},
            new Transaction(){ReserveDate=DateTime.Now,ReturnDate=DateTime.Now.AddDays(5),UserId= new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),VideoId=new Guid("bcfc276a-8c41-40ad-bb7b-05731dbfcce5")}
 
        };
        Transactions.ForEach(x => context.TranactionSet.Add(x));
 
        context.SaveChanges();
        
       base.Seed(context);
    }
}
 

6. Edit the config
Add context to the entity framework
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
    <contexts>
      <context type="SEF_CodeFirst_API.Models.DbModels.RentalContext, SEF_CodeFirst_API">
        <databaseInitializer type="EF_CodeFirst_API.Models.DbModels.RentalInitializer, SEF_CodeFirst_API" />
      </context>
    </contexts>
  </entityFramework>

Add the  Connection string
 <connectionStrings>
    <add name="RentalContext" 
 connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Rental;Integrated Security=SSPI;" 
 providerName="System.Data.SqlClient" />
  </connectionStrings>


Then  you have to create Controller's from Entity framework with read write options.. you are in


Enjoy



1 comments:

Mahbuba Islam said...

Beetechnical is one of the developing free visitor blogging stages on the web. It is best blogging platform . It is free guest blogging platform for earning money where enable every single enthusiastic writer out there who wanna bother free writing. Beetechnical is mainly for passionate Writers and Guest Bloggers. Free tech guest blogging site .