1. 创建数据库上下文(DbContext)类:

 using System.Data.Entity;  
 
   
 
 public class MyDbContext : DbContext  
 
 {  
 
     public MyDbContext() : base("MyDbContext")  
 
     {  
 
     }  
 
   
 
     public DbSet<MyEntity> MyEntities { get; set; }  
 
 }
  1. 创建实体类:

 public class MyEntity  
 
 {  
 
     public int Id { get; set; }  
 
     public string Name { get; set; }  
 
 }
  1. 在Web.config中配置数据库连接字符串:

 <connectionStrings>  
 
   <add name="MyDbContext" connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />  
 
 </connectionStrings>
  1. 添加新的数据:

 using (var context = new MyDbContext())  
 
 {  
 
     var entity = new MyEntity { Name = "John" };  
 
     context.MyEntities.Add(entity);  
 
     context.SaveChanges();  
 
 }
  1. 查询数据:

 using (var context = new MyDbContext())  
 
 {  
 
     var entities = context.MyEntities.ToList();  
 
     foreach (var entity in entities)  
 
     {  
 
         Console.WriteLine(entity.Name);  
 
     }  
 
 }
  1. 更新数据:

 using (var context = new MyDbContext())  
 
 {  
 
     var entity = context.MyEntities.FirstOrDefault(e => e.Id == 1);  
 
     if (entity != null)  
 
     {  
 
         entity.Name = "Jane";  
 
         context.SaveChanges();  
 
     }  
 
 }
  1. 删除数据:

 using (var context = new MyDbContext())  
 
 {  
 
     var entity = context.MyEntities.FirstOrDefault(e => e.Id == 1);  
 
     if (entity != null)  
 
     {  
 
         context.MyEntities.Remove(entity);  
 
         context.SaveChanges();  
 
     }  
 
 }