Get started with Code first Db context simple select


Getting starting with Entity framework code first


Youtube link


Step 1. Install entity framework from Nuget



you can find it on installed section whether it is installed or not.


 Step 2. Add connection string for the sql communication.


 Step 3: Add class with matches with sql table.

use sp_help to use structure of table
sp_help customers
 match nvarchar with string datatype name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace EntityFramworkd_Code_First.Models
{
    public class Customer
    {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string Phone { get; set; }
        public string Fax { get; set; }
    }
}

Step 4: Add a db context class



using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using EntityFramworkd_Code_First.Models;

namespace EntityFramworkd_Code_First.Context
{
    public class NorthwindContext: DbContext
    {
        public NorthwindContext(): base("name=NorthwindDBConnectionString")
        {

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

}

pass the connection string name inside base function.


 Dbset will try to look for matching names


Step 5 : Create a object of dbcontext and get the data using context.set method.

       public ActionResult Index()
        {
            using (var ctx = new NorthwindContext())
            {
                 var cust = ctx.Set<Customer>().ToList();
              
            }
                return View();
        }





Share on Google Plus

About myzingonline

Myzingonline is all about zing to share experience, knowledge, likes, dislikes and ideas of a person to the world.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment