首页 > 代码库 > EF6.0+APS.NET MVC5.0项目初探三(code first实体映射到数据库)
EF6.0+APS.NET MVC5.0项目初探三(code first实体映射到数据库)
到这里架构就搭建完了,该向里面填充东西的时候了,如上篇:EF6.0+APS.NET MVC5.0项目初探二(类库引用关系及说明)
第一步 :在需要添加EF的类库Domain.DbContext上右击-》管理NuGet程序包-》找到Entity FrameWork下载安装。
如图:
第二步:新建DbContext
第三步:在类库Domain.Entity上添加引用System.ComponentModel.DataAnnotations(用于验证的引用) 并新建实体类。
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel.DataAnnotations; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace Domain.Entity 9 {10 public abstract class BaseEntity11 {12 //如果类的属性名为“ID”(不区分大小写)或类名的后面跟有“ID”,则 Code First 会推断该属性是主键。如果主键属性的类型为数值或 GUID,则将其配置为标识列。13 //int类型的自动定义为自增长 14 //自定义增长方式15 //[System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]16 [Key]17 [Display(Name = "编号")]18 public int Id { get; set; }19 [Display(Name = "排序")]20 [Required(ErrorMessage = "必填项{0}!"), Range(0, int.MaxValue, ErrorMessage = "必填项{0}!")]21 public int Sort { get; set; }22 [Display(Name = "备注")]23 [MaxLength(64, ErrorMessage = "{0}最大长度{1}!")]24 public string Remark { get; set; }25 [Display(Name = "是否删除")]26 public bool Deleted { get; set; }27 public int? AddUser { get; set; }28 [DisplayFormat(ApplyFormatInEditMode = true, ConvertEmptyStringToNull = true, DataFormatString = "{0:yyyy-MM-dd HH mm}", HtmlEncode = false, NullDisplayText = "数据无效")]29 public DateTime? AddTime { get; set; }30 public int? ModUser { get; set; }31 [DisplayFormat(ApplyFormatInEditMode = true, ConvertEmptyStringToNull = true, DataFormatString = "{0:yyyy-MM-dd HH mm}", HtmlEncode = false, NullDisplayText = "数据无效")]32 public DateTime? ModTime { get; set; }33 34 //详见:http://msdn.microsoft.com/zh-cn/data/jj591583.aspx35 //主键:KEY [Key]36 //自增长 :[System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated (System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]37 //忽略列 忽略表 映射 :[NotMapped]38 //定义外键方式:[ForeignKey("DestinationId")]39 //定义数据类型 [Column(TypeName = "ntext")]40 //表名及所有者 [Table("Product", Schema = "dbo")]41 }42 }
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel.DataAnnotations; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace Domain.Entity 9 {10 public class T_Public_AdPosition:BaseEntity11 {12 [Display(Name = "广告位名称")]13 [Required(ErrorMessage="{0}是必填项")]14 [MaxLength(64, ErrorMessage = "{0}最大长度{1}")] 15 public string Name { get; set; }16 [Display(Name = "广告位宽度")]17 [Required(ErrorMessage = "{0}是必填项")]18 public int Width { get; set; }19 20 [Display(Name = "广告位长度")]21 [Required(ErrorMessage = "{0}是必填项")]22 public int Height { get; set; }23 24 [Display(Name = "广告位模板")]25 [Required(ErrorMessage = "{0}是必填项")]26 [MaxLength(128, ErrorMessage = "{0}最大长度{1}")]27 public string Template { get; set; }28 }29 }
第四步:修改类库Domain.DbContext中的App.config文件和UI.Manage中的webconfig文件,添加连接。其中的数据库名称就是将要生成的数据库名称
<connectionStrings> <add name="LimitDB" connectionString="Data Source=.;Initial Catalog=LimitDB;User ID=sa;Password=123456;MultipleActiveResultSets=True;Application Name=EntityFramework" providerName="System.Data.SqlClient" /> </connectionStrings>
name="LimitDB"是数据库连接名称,
Initial Catalog=LimitDB是将要生成的数据库名称
App.config文件如下,webconfig文件类似修改连接
1 <?xml version="1.0" encoding="utf-8"?> 2 <configuration> 3 <configSections> 4 <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> 5 <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> 6 </configSections> 7 <connectionStrings> 8 <add name="LimitDB" connectionString="Data Source=.;Initial Catalog=LimitDB;User ID=sa;Password=123456;MultipleActiveResultSets=True;Application Name=EntityFramework" providerName="System.Data.SqlClient" /> 9 </connectionStrings>10 <entityFramework>11 <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">12 <parameters>13 <parameter value=http://www.mamicode.com/"v11.0" />14 </parameters>15 </defaultConnectionFactory>16 <providers>17 <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />18 </providers>19 </entityFramework>20 </configuration>
第五步:执行数据库迁移命令
如图:
生成如下文件:
修改生成的文件:
1 namespace Domain.DbContext.Migrations 2 { 3 using System; 4 using System.Data.Entity; 5 using System.Data.Entity.Migrations; 6 using System.Linq; 7 8 internal sealed class Configuration : DbMigrationsConfiguration<Domain.DbContext.DbContext> 9 {10 public Configuration()11 {12 //允许自动迁移13 //不然会报错Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.You can use the Add-Migration command to write the pending model changes to a code-based migration.14 15 //允许自动迁移16 AutomaticMigrationsEnabled = true;17 //自动迁移默认情况下不扔掉列在我们的数据库中的表。如果我们不希望这样的行为,我们可以告诉迁移明确允许数据丢失的配置类的AutomaticMigrationDataLossAllowed属性设置为true。18 AutomaticMigrationDataLossAllowed = true;19 }20 21 protected override void Seed(Domain.DbContext.DbContext context)22 {23 // This method will be called after migrating to the latest version.24 25 // You can use the DbSet<T>.AddOrUpdate() helper extension method 26 // to avoid creating duplicate seed data. E.g.27 //28 // context.People.AddOrUpdate(29 // p => p.FullName,30 // new Person { FullName = "Andrew Peters" },31 // new Person { FullName = "Brice Lambson" },32 // new Person { FullName = "Rowan Miller" }33 // );34 //35 }36 }37 }
第六步:在程序包管理器控制台执行更新数据库命令:Update-Database 以后每次更改模型都可以执行此命令将对应的model更新到数据库
到这里,code first 实体映射数据库就完成了。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。