Pages

Tuesday, October 9, 2018

Entity Framework Connectivity VS2015


/****** Object:  Table [dbo].[Employee]    ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Employee1](
[HREmpId] [numeric](18, 0) NOT NULL,
[FirstName] [nchar](10) NULL
) ON [PRIMARY]

GO


------------------------------------------------------------------------------------------------------------------


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


public class MyContext:DbContext

{
    public MyContext() :base("DefaultConnection")
    {
        //Database.SetInitializer<MyContext>(new CreateDatabaseIfNotExists<MyContext>());
    }

     virtual public DbSet<Employee> employee { get; set; }
}

---------------------------------------------------------------------------------------------------------------------
using System.ComponentModel.DataAnnotations;


public class Employee
{
    [Key]
    public decimal HREmpId { get; set; }
    public string FirstName { get; set; }
 

}

-------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        using (MyContext m = new MyContext())
        { var s="";
            foreach (var a in m.employee)
            {
                s = s + a.FirstName;
            }
            Response.Write(s);
        }
     }
}

-------------------------------------------------------------------------------------------------------------------------
<connectionStrings>
    <add name="DefaultConnection"
      connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=LearnEF;Persist Security Info=True;User ID=sa;password=123456"
      providerName="System.Data.SqlClient"/>
  </connectionStrings>

No comments:

Post a Comment