Entity Framework联接数据信息库、原始化的一些专业

摘要: 老话说:“磨刀不误砍柴工工欲善其事”,在深层次解读Entity Framework以前,先提前准备一下开发设计专用工具及其早期的配备。一、开发设计专用工具开发设计专用工具基本忽略,这儿...

老话说:“磨刀不误砍柴工工欲善其事”,在深层次解读Entity Framework以前,先提前准备一下开发设计专用工具及其早期的配备。

一、开发设计专用工具

开发设计专用工具基本忽略,这儿说一下,我应用的是Visual Studio 2012,Entity Framework版本号为4.3.1,获得这一版本号的方法:在Package Manager Console中键入Install-Package EntityFramework -Version 4.3.1。对于数据信息库,关键是LocalDb。

二、联接数据信息库

当应用NuGet安裝完Entity Framework后,在配备文档时会全自动添加entityFramework节,里边有defaultConnectionFactory原素,以下:

 1: ?xml version="1.0" encoding="utf-8"? 
 2: configuration 
 3: configSections 
 4: !-- rmation on Entity Framework configuration, visit fwlink/?LinkID=237468 -- 
 5: section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" / 
 6: /configSections 
 7: entityFramework 
 8: defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" 
 9: parameters 
 10: parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" / 
 11: /parameters 
 12: /defaultConnectionFactory 
 13: /entityFramework 
 14: /configuration 

在沒有出示实际数据信息库联接的状况下,EF默认设置应用这一配备。如上边编码中,默认设置会联接到LocalDb,数据信息库的名字为左右文彻底限制名(取名室内空间+类名)。之前常常提及默认设置联接到.\SQLEXPRESS,由于安裝的版本号不一样。

EF中出示了2个联接加工厂:SqlConnectionFactory和SqlCeConnectionFactory。应用方法各自以下:

 1: Database.DefaultConnectionFactory = new SqlConnectionFactory("Data Source=.;Database=Test;UId=sa;Pwd=sasa;MultipleActiveResultSets=True");

 1: Database.DefaultConnectionFactory = new SqlConnectionFactory("Data Source=.;Database=Test;User=sa;Password=sasa;MultipleActiveResultSets=True");

 1: Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");

在配备文档和编码中通时有DefaultConnectionFactory的状况下,编码中的优先选择。

下边,写一个简易的操纵台程序。编码以下:

 1: namespace ConnectDatabase
 2: {
 3: class Program
 4: {
 5: static void Main(string[] args)
 6: {
 7: using (TestContext ctx = new TestContext())
 8: {
 9: var blog = new Blog()
 10: {
 11: Name = "EF"
 12: };
 13: blog.Posts.Add(new Post()
 14: {
 15: Title = "联接数据信息库",
 16: Content = "它是联接数据信息库的检测",
 17: Creationdate = DateTime.Now,
 18: Blog = blog
 19: });
 20: ctx.Blogs.Add(blog);
 21: ctx.SaveChanges();
 22: 
 23: foreach (var item in ctx.Blogs)
 24: {
 25: Console.WriteLine(item.Name);
 26: }
 27: }
 28: }
 29: }
 30: 
 31: public class TestContext : DbContext
 32: {
 33: protected override void OnModelCreating(DbModelBuilder modelBuilder)
 34: {
 35: base.OnModelCreating(modelBuilder);
 36: }
 37: 
 38: public DbSet Blog Blogs { get; set; }
 39: public DbSet Post Posts { get; set; }
 40: }
 41: 
 42: public class Blog
 43: {
 44: public Blog()
 45: {
 46: Posts = new List Post 
 47: }
 48: 
 49: public int Id { get; set; }
 50: public string Name { get; set; }
 51: public virtual List Post Posts { get; set; }
 52: }
 53: 
 54: public class Post
 55: {
 56: public int Id { get; set; }
 57: public string Title { get; set; }
 58: public string Content { get; set; }
 59: public DateTime Creationdate { get; set; }
 60: public virtual Blog Blog { get; set; }
 61: }
 62: }

应用默认设置联接配备,转化成的数据信息库名字为:ConnectDatabase.TestContext,以下图所显示:

重新写过上边配备有下列方式:

1.在配备文档中加上connectionStrings,name和左右文类名一致。

 1: connectionStrings 
 2: add name="TestContext1" connectionString="Data Source=(localdb)\v11.0;Database=Test;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/ 
 3: /connectionStrings 

2.同1,可是name和左右文类名不一致。这就必须改动TextContext编码,以下:

 1: public TestContext() : this("TestContext1") { }
 2: 
 3: public TestContext(string nameOrConnectionString)
 4: : base(nameOrConnectionString)
 5: {
 6: 
 7: }

 1: public TestContext()
 2: : base("name=TestContext1")
 3: {
 4: 
 5: }

 1: public TestContext():base("TestContext1"){}

下边得出联接实际数据信息库的配备:

1.联接Sql Server数据信息库

 1: connectionStrings 
 2: add name="TestContext" connectionString="Data Source=.;Database=Test;User=sa;Password=sasa;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/ 
 3: /connectionStrings 

2.联接Sql Server Compact 4.0

 1: connectionStrings 
 2: add name="TestContext" connectionString="Data Source=|DataDirectory|\Test.sdf" providerName="System.Data.SqlServerCe.4.0"/ 
 3: /connectionStrings 

3.联接MySql 5.5

-6.6.4,文中最终出示这种专用工具的免费下载详细地址。

 1: connectionStrings 
 2: add name="TestContext"
 3: connectionString="User Id=root;server=localhost;password=sasa;database=test1"
 4: providerName="MySql.Data.MySqlClient" / 
 5: /connectionStrings 

三、数据信息库原始化

1.关掉原始化

 1: Database.SetInitializer TestContext (null);

2.CreateDatabaseIfNotExists

它是Entity Framework的默认设置原始化对策,沒有必需设定它,假如确实必须设定,以下:

 1: Database.SetInitializer(new CreateDatabaseIfNotExists TestContext 

3.DropCreateDatabaseWhenModelChanges

假如实体模型产生了更改,则删掉并举建数据信息库。

 1: Database.SetInitializer(new CreateDatabaseIfNotExists TestContext 

4.DropCreateDatabaseAlways

不管实体模型和数据信息库配对是否,都删掉并举建数据信息库。

 1: Database.SetInitializer(new DropCreateDatabaseAlways TestContext 

5.Database.Initialize能够强制性原始化,即便在当今AppDomain中早已产生了。下边我写个模块检测程序,来演试这一点:

 1: [TestClass]
 2: public class UnitTest1
 3: {
 4: [TestMethod]
 5: public void TestForceInitialize()
 6: {
 7: //表明一点:我Demo中的TestContext和Microsoft.VisualStudio.TestTools.UnitTesting.TestContext矛盾了,因此写出了ConnectDatabase.TestContext
 8: //Arrage
 9: Database.SetInitializer(new DropCreateDatabaseAlways ConnectDatabase.TestContext 
 10: //Act
 11: using (ConnectDatabase.TestContext ctx = new ConnectDatabase.TestContext())
 12: {
 13: ctx.Database.Initialize(force: true);
 14: ctx.Blogs.Add(new ConnectDatabase.Blog()
 15: {
 16: Name = "强制性原始化1"
 17: });
 18: ctx.SaveChanges();
 19: }
 20: using (ConnectDatabase.TestContext ctx = new ConnectDatabase.TestContext())
 21: {
 22: ctx.Database.Initialize(force: true);
 23: ctx.Blogs.Add(new ConnectDatabase.Blog()
 24: {
 25: Name = "强制性原始化2"
 26: });
 27: ctx.SaveChanges();
 28: }
 29: ConnectDatabase.Blog blog = null;
 30: using (ConnectDatabase.TestContext ctx = new ConnectDatabase.TestContext())
 31: {
 32: blog = ctx.Blogs.FirstOrDefault();
 33: }
 34: 
 35: //Assert
 36: Assert.IsNotNull(blog);
 37: Assert.AreEqual("强制性原始化2", blog.Name);
 38: 
 39: }
 40: }

检测結果:

由于设定的原始化对策为DropCreateDatabaseAlways,每一次启用Database.Initialize,主要参数为true,都是再次删掉并建立数据信息库。

四、Seed数据信息

建立数据信息库时原始化一些数据信息,最先自定原始化对策,重新写过Seed方式,编码以下:

 1: public class DropCreateDatabaseWithSeedData : DropCreateDatabaseAlways TestContext 
 2: {
 3: protected override void Seed(TestContext context)
 4: {
 5: context.Blogs.Add(new Blog()
 6: {
 7: Name = "種子数据信息1"
 8: });
 9: context.Blogs.Add(new Blog()
 10: {
 11: Name = "種子数据信息2"
 12: });
 13: //留意沒有启用context.SaveChanges(),base.Seed(context)会启用
 14: base.Seed(context);
 15: }
 16: }

下边是检测程序:

 1: [TestMethod]
 2: public void SeedData()
 3: {
 4: Database.SetInitializer(new DropCreateDatabaseWithSeedData());
 5: List ConnectDatabase.Blog blogList = null;
 6: using (ConnectDatabase.TestContext ctx = new ConnectDatabase.TestContext())
 7: {
 8: blogList = ctx.Blogs.OrderBy(t = t.Id).ToList();
 9: }
 10: Assert.AreEqual(2, blogList.Count);
 11: Assert.AreEqual("種子数据信息1", blogList[0].Name);
 12: Assert.AreEqual("種子数据信息2", blogList[1].Name);
 13: }

检测結果:

五、建立数据库索引

在Seed方式中,应用ExecuteSqlCommand建立数据库索引,编码以下:

 1: protected override void Seed(TestContext context)
 2: {
 3: context.Database.ExecuteSqlCommand("CREATE INDEX IX_Test_Name ON Blogs (Name)");
 4: context.Blogs.Add(new Blog()
 5: {
 6: Name = "種子数据信息1"
 7: });
 8: context.Blogs.Add(new Blog()
 9: {
 10: Name = "種子数据信息2"
 11: });
 12: //留意沒有启用context.SaveChanges(),base.Seed(context)会启用
 13: base.Seed(context);
 14: }


联系我们

全国服务热线:4000-399-000 公司邮箱:343111187@qq.com

  工作日 9:00-18:00

关注我们

官网公众号

官网公众号

Copyright?2020 广州凡科互联网科技股份有限公司 版权所有 粤ICP备10235580号 客服热线 18720358503

技术支持:如何开发小程序