EntityFramework使用总结(与MVC4.0实现CURD操作)
本篇文介绍一下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=ERICSQLEXPRESS;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