本篇文介绍一下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为学生信息实体类,并关联数据库表和其他一些属性说明,代码如下
View Code
说明:用属性Key说明的字段如果是int类型,EF会默认该字段对应的数据库表字段是自增的,好像是这样的,说的不对的请纠正。
2、DbHelper.cs主要创建数据库上下文,代码如下:cpysgxlyxftcefuafwtrlmym
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; } } }
<strong>说明:这里还需要请用<span style=
"color: #000000;"
>System.Data.Entity.</span>DLL</strong>
|
<strong>要不然会报如下的一个错误:</strong>
|
四、我们创建表tb_Students和存储过程proc_1
tb_Students
proc_1
五、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的学习资料欢迎共享共同学习