1.添加数据库连接串
<configuration>
<connectionStrings> <add name="MYConnection" connectionString="Data Source=.;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=123456;" providerName="System.Data.SqlClient" /> </connectionStrings></configuration>
2.创建实体映射关系
public class PeopleMap : EntityTypeConfiguration<People>
{ public PeopleMap() { //设置主键 this.HasKey(t => t.id);//设置验证
this.Property(t => t.name).HasMaxLength(10).IsOptional();//设置对应的表
this.ToTable("People");//设置与数据库对应的字段
this.Property(t => t.id).HasColumnName("id"); this.Property(t => t.age).HasColumnName("age"); this.Property(t => t.name).HasColumnName("name");}
}3.实现DBContext类,创建数据库连接串
/// <summary>
/// 数据库连接串 /// </summary> public class MyDbContext:DbContext { public MyDbContext() : base("name=MYConnection") {}
public DbSet<People> peoples { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)//添加实体映射关系表
{ base.OnModelCreating(modelBuilder);modelBuilder.Configurations.Add(new PeopleMap());
}}
4.增删改查基本方法
public void getEFAdd() { using (var con = new MyDbContext()) {con.peoples.Add(new People()
{ id = 2, name = "吴彦祖", age = 12 });con.SaveChanges();
} }public void getRemove()
{ using (var con = new MyDbContext()) { var p = con.peoples.FirstOrDefault(t => t.id == 2); if (p != null) { con.peoples.Remove(p); } con.SaveChanges(); } }public void getUpdate()
{ using (var con = new MyDbContext()) { People p = con.peoples.Find(1); p.age = 20; con.SaveChanges(); } }public void getData()
{ using (var con = new MyDbContext()) { List<People> list = con.peoples.Where(t => t.id > 0).ToList<People>(); } }5.前台调用
function add() {
alert("add"); $.ajax({ type: "POST", contentType: "application/json", url: "EF/getEFAdd", dataType: 'text', async: true, success: function (res) { alert(res); } }) }