Entity Framework 6.1-Code First

简介: 原文: Entity Framework 6.1-Code First Code First-代码优先,先创建好领域模型。新建MyDbContext继承DbContext。
原文: Entity Framework 6.1-Code First

Code First-代码优先,先创建好领域模型。新建MyDbContext继承DbContext。根据代码自动生成数据库

Code First优点

1.可以自由的创建领域模型,基本不受EF框架的限制。自由的命名。程序员只需要关心对象间的关系。基本做到了与数据库的完全分离。

2.便于单元测试。不再使用绑定性较强的edmx文件。只使用普通的Model类

3.使用Fluent API映射可以自由的定义表名、字段名和关系。可控性强

4.可以方便的进行数据库迁移


用法

一、创建领域模型:新建Contact、CGroup、Address三个Model类

public class Contact
  {
        public int ID { get; set; }
        public string Name { get; set; }
        public System.DateTime CreateDate { get; set; }
        public virtual Address Address { get; set; }
        public int CGroupID { get; set; }
        public CGroup CGroup { get; set; }
        public virtual ICollection<Book> Books { get; set; }
    }


    public class CGroup
    {
        public int Id { get; set; }
        public string GName { get; set; }
        public ICollection<Contact> Contacts { get; set; }
    }
    public class Address
    {
        public int ID { get; set; }
        public string Contury { get; set; }
        public string City { get; set; }
        public string Street { get; set; }
        public string Code { get; set; }
        public Contact Contact { get; set; }
    }

二、新建一个EFTestContext,继承自DbContext

 public class EFTestContext : DbContext
  {
        public EFTestContext() : base("name=CommunicationContext2") { }


        public DbSet<EFModels.CGroup> CGroups { get; set; }
        public DbSet<EFModels.Address> Addresses { get; set; }
        public DbSet<EFModels.Contact> Contacts { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<EasyUIEFWebApp.DAL.EFModels.Contact>().HasOptional(c => c.Address)
                .WithOptionalDependent(add => add.Contact);
            modelBuilder.Entity<EasyUIEFWebApp.DAL.EFModels.CGroup>().HasMany(c => c.Contacts)
                .WithRequired(c => c.CGroup).WillCascadeOnDelete(false);
            //modelBuilder.Entity<EasyUIEFWebApp.DAL.EFModels.Contact>().HasOptional(c => c.CGroup)
            //    .WithMany(c => c.Contacts).WillCascadeOnDelete(true);
        }
   }

注意:base("name=CommunicationContext2") { },这句表示使用Config文件里名为CommunicationContext2的数据库连接,如果直接写base("CommunicationContext2") { }

EF会自动创建一个名为CommunicationContext2的dbf文件。数据库名也是CommunicationContext2

三、Code First三种数据库创建模式

1.DropCreateDatabaseAlways

表示每次都重新创建数据库。适用于较小的项目前期开发。数据库和模型经常变动。使用的几率较小。使用方法:在程序启动方法中添加

 Database.SetInitializer(new DropCreateDatabaseAlways<EFTestContext>());

2.DropCreateDatabaseIfModelChanges

表示每次模型改变时都重新创建数据库。项目前期开发,数据库和模型变动比较多。使用方法:在程序启动方法中添加

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EFTestContext>());

3.MigrateDatabaseToLatestVersion

使用迁移数据库的最新版本。需要配合数据库迁移使用。

 数据库迁移(Migrations)

1.工具-》库程序包管理-》程序包管理器控制台,打开程序包管理器控制台。

输入Enable-Migrations,回车执行


会在项目中创建Migrations文件夹。Migrations文件夹下自动创建一个Configuration类,继承DbMigrationsConfiguration<EasyUIEFWebApp.DAL.EFTestContext>

internal sealed class Configuration : DbMigrationsConfiguration<EasyUIEFWebApp.DAL.EFTestContext>
 {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }


        protected override void Seed(EasyUIEFWebApp.DAL.EFTestContext context)
        {
            //  This method will be called after migrating to the latest version.


            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            // 在运行update-database时执行
            context.Addresses.AddOrUpdate(new EasyUIEFWebApp.DAL.EFModels.Address
            {
                Contury = "Amerca",
                City = "New York",
                Street = "Man Hand",
                Code = "560012",
                GateCode = "A 10"
            });
        }
    }

2.再运行Add-Migrations InitialCreate  命令。会Migrations在新建一个名为[DateStamp]_InitialCreate 的类,把现有的Model类生成数据库代码。如下

public partial class InitialCreate : DbMigration
  {
        public override void Up()
        {
            CreateTable(
                "dbo.Addresses",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        Contury = c.String(),
                        City = c.String(),
                        Street = c.String(),
                        Code = c.String(),
                        GateCode = c.String(),
                    })
                .PrimaryKey(t => t.ID);
            
            CreateTable(
                "dbo.Contacts",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                        CreateDate = c.DateTime(nullable: false),
                        CGroupID = c.Int(nullable: false),
                        Phone = c.String(),
                        Mobile = c.String(),
                        Address_ID = c.Int(),
                    })
                .PrimaryKey(t => t.ID)
                .ForeignKey("dbo.Addresses", t => t.Address_ID)
                .ForeignKey("dbo.CGroups", t => t.CGroupID)
                .Index(t => t.CGroupID)
                .Index(t => t.Address_ID);
            
            CreateTable(
                "dbo.CGroups",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        GName = c.String(),
                        GAuthor = c.String(),
                    })
                .PrimaryKey(t => t.Id);
            
        }
        
        public override void Down()
        {
            DropForeignKey("dbo.Contacts", "CGroupID", "dbo.CGroups");
            DropForeignKey("dbo.Contacts", "Address_ID", "dbo.Addresses");
            DropIndex("dbo.Contacts", new[] { "Address_ID" });
            DropIndex("dbo.Contacts", new[] { "CGroupID" });
            DropTable("dbo.CGroups");
            DropTable("dbo.Contacts");
            DropTable("dbo.Addresses");
        }
 }


3.再运行Update-Database,生成数据库

4.模型有改动是运行Add-Migrations -Force InitialCreate命令,生成数据库的变更代码。命名为[DateStamp]_InitialCreate1

5。再次运行运行Update-Database,更新数据库。也可以在程序运行时运行

Database.SetInitializer(new MigrateDatabaseToLatestVersion<EFTestContext,Configuration>());代码,每次都会检查挂起的模型更改,迁移成最新的数据库。

6.可以单独生成sql,而不直接运行。运行Update-Database -Script –SourceMigration:开始的数据库版本 –TargetMigration:结束的数据库版本(可省略,表示到最新的)命令

 

四、测试

跟DBFrist、model first使用方法一样



目录
相关文章
|
数据库
Entity Framework Core介绍(1)
介绍 Entity Framework (EF) Core 是轻量化、可扩展和跨平台版的常用 Entity Framework 数据访问技术。 EF Core 可用作对象关系映射程序 (O/RM),以便于 .NET 开发人员能够使用 .NET 对象来处理数据库,这样就不必经常编写大部分数据访问代码了。
960 0
|
索引
Entity Framework 小知识(四)
Entity Framework 小知识(四)
116 0
|
数据库 数据库管理
Entity Framework 小知识(一)
Entity Framework 小知识(一)
107 0
|
SQL 数据库
Entity Framework 小知识(二)
Entity Framework 小知识(二)
148 0
|
数据库
Entity Framework 小知识(五)
Entity Framework 小知识(五)
119 0
|
数据库
Entity Framework 小知识(三)
Entity Framework 小知识(三)
129 0