Code First是Entity Framework提供的一种新的编程模型。通过Code First我们可以在还没有建立数据库的情况下就开始编码,然后通过代码来生成数据库。下面具体讲解一下,在操作的时候可能会出现的错误,
主要分为一下几大步骤,
1. 安装Entity Framework
2. Entity Framework数据库连接配置
<add name="BreakAwayContext" connectionString="data source=.;initial catalog=CodeFirstDemoDB;persist security info=True;user id=sa;password=123456;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
3. Entity Framework DbContext连接数据库
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace Portal { public class PortalContext : DbContext { static PortalContext() { Database.SetInitializer<PortalContext>(null); } public PortalContext() : base("name=PortalContext") { // 禁用延迟加载 this.Configuration.LazyLoadingEnabled = false; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // 禁用默认表名复数形式 modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); // 禁用一对多级联删除 modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); // 禁用多对多级联删除 modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>(); } } }
最后 测试一个控制台程序执行完毕后即可插入到数据库中。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeFirstProject { class Program { static void Main(string[] args) { var d = DateTime.Now.Date.ToString("yyyyMM"); var destination = new Destination { Country = "China", Description = "China Is Friendly", Name = "Chinese" }; using (var context = new BreakAwayContext()) { context.Destinations.Add(destination); context.SaveChanges(); } Console.WriteLine("OK"); } } }
以上便是最入门的CodeFirst讲解,如有不好的地方还望指教,欢迎留言交流!
时间: 2024-10-09 10:05:02