本篇文介紹一下Entity Framework Code First的簡單用法,通過一個學生信息的增刪查改來學習Entity Framework的使用及與存儲過程的交互。我也是學習Entity Framework新手,有說的不對地方歡迎指正。
本文使用的開發環境為VS2010(sp1)+MVC4.0+EF5.0。
一、我們新建一個空MVC空項目
添加EntityFramework.dll的引用。
二、修改配web.config置文件(web.config為根目錄下的)
添加EntityFramework配置和數據庫連接字符串。
<configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> </entityFramework> <connectionStrings> <add name="strConn" connectionString="Data Source=ERIC\SQLEXPRESS;Initial Catalog=EfSample;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings>
三、在Models文件夾下新建Students.cs和DbHelper.cs
1、Students為學生信息實體類,並關聯數據庫表和其他一些屬性說明,代碼如下

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace MVCEF.Models { [Table("tb_Students", Schema = "dbo")]//關聯數據表 dbo.tb_Students public class Students { [Key] public string Num { get; set; } [MaxLength(10),Required(ErrorMessage="姓名不能為空")] [Column(TypeName = "nvarchar")] public string Name { get; set; } public int Age { get; set; } [MaxLength(10)] [Column(TypeName = "varchar")] public string Sex { get; set; } [MaxLength(50)] public string Class { get; set; } } }
說明:用屬性Key說明的字段如果是int類型,EF會默認該字段對應的數據庫表字段是自增的,好像是這樣的,說的不對的請糾正。
2、DbHelper.cs主要創建數據庫上下文,代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.Data.Entity.Migrations; namespace MVCEF.Models { public class DbHelper:DbContext { public DbHelper() : base("strConn") { //自動創建表,如果Entity有改到就更新到表結構 Database.SetInitializer<DbHelper>(new MigrateDatabaseToLatestVersion<DbHelper, ReportingDbMigrationsConfiguration>()); } public DbSet<Students> Students { get; set; } } internal sealed class ReportingDbMigrationsConfiguration : DbMigrationsConfiguration<DbHelper> { public ReportingDbMigrationsConfiguration() { AutomaticMigrationsEnabled = true;//任何Model Class的修改將會直接更新DB AutomaticMigrationDataLossAllowed = true; } } }
說明:這里還需要請用System.Data.Entity.DLL

要不然會報如下的一個錯誤:

四、我們創建表tb_Students和存儲過程proc_1

CREATE TABLE [dbo].[tb_Students]( [Num] [varchar](128) NOT NULL, [Name] [nvarchar](10) NOT NULL, [Age] [int] NULL, [Sex] [varchar](10) NULL, [Class] [nvarchar](50) NULL, PRIMARY KEY CLUSTERED ( [Num] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO

create proc proc_1 @Num varchar(128), @Name varchar(50) as select * from dbo.tb_Students where Num=@Num and Name=@Name
五、HomeController.cs調用EF方法實現增刪改查。
方法都比較簡單,這里就不做詳細說明了
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVCEF.Models; using System.Data; using System.Data.SqlClient; namespace MVCEF.Controllers { public class HomeController : Controller { DbHelper db = new DbHelper(); private static List<Students> listStu = new List<Students>() { new Students(){Num="s0001",Name="張三",Age=19,Sex="man",Class="計算機1班"}, new Students(){Num="s0002",Name="李四",Age=20,Sex="man",Class="計算機1班"}, new Students(){Num="s0003",Name="王五",Age=18,Sex="man",Class="計算機1班"}, new Students(){Num="s0004",Name="小紅",Age=17,Sex="women",Class="計算機'\"1班"}, }; // // GET: /Home/ public ActionResult Index() { //如果沒有數據初始化數據 if (db.Students.Count() == 0) { listStu.ForEach(it => { db.Students.Add(it); }); db.SaveChanges(); } List<Students> lst = db.Students.ToList(); //實現2:sql語句實現 //List<Students> lst = db.Students.SqlQuery("select * from tb_Students").ToList(); //與存儲過程交互 // var result = db.Database.SqlQuery<Students>("exec proc_1 @p0,@p1", "s0001","張三1").ToList(); return View(lst); } public ActionResult Add() { return View(new Students()); } [HttpPost] public ActionResult Add(Students stu) { string Message = string.Empty; if (db.Students.Where(it => it.Num == stu.Num).FirstOrDefault()!=null) { Message = "學號已經存在"; ViewBag.Msg = Message; return View(); } db.Students.Add(stu); db.SaveChanges(); return RedirectToAction("Index","Home"); } public ActionResult edit(string id) { var stu=db.Students.Where(it => it.Num == id).FirstOrDefault(); return View(stu); } [HttpPost] public ActionResult edit(Students stu, FormCollection form,string id) { stu.Num = id; db.Entry(stu).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index", "Home"); } //刪除 public ActionResult Del(string id) { /*方法1 var stu = db.Students.Where(it => it.Num == id).FirstOrDefault(); db.Entry(stu).State = EntityState.Deleted; db.SaveChanges(); */ //方法2 string strsql = "delete from tb_Students where Num=@Num"; SqlParameter[] paras = { new SqlParameter("@Num",SqlDbType.NVarChar,128) }; paras[0].Value=id; db.Database.ExecuteSqlCommand(strsql, paras); db.SaveChanges(); return RedirectToAction("Index", "Home"); } } }
六、EF與存儲過程交互
EF與存儲過程交互詳見Index方法: var result = db.Database.SqlQuery<Students>("exec proc_1 @p0,@p1", "s0001","張三1").ToList();
其中@p0,@p1為傳入存儲過程中的參數(依次對應存儲過程參數@Num和@Name)。
我們在使用EF調用存儲過程的時候傳入的參數為@p0,@p1,@p2,@p3 依此排列下去(蛋疼不知道為啥這樣設計)
但是如何獲取存儲過程的返回值和out參數我還沒有找到,如果你知道希望能留下你的答案,共同學習。
如果你有什么更好的關於EF的學習資料歡迎共享共同學習
點擊下載源碼
每天學習一點點,每天進步一點點