EF Codefirst入门之创建数据库

  实验环境是VS 2015、MSSQL Server 2008、windows 10

一、创建项目

  通过VS创建一个MVC5项目EntityFrameworkExtension

二、安装Entity Framework

  通过nuget添加Entity Framework到项目,当前版本为6.2.0

三、创建实体类Student  

public class Student
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

    }

四、添加数据库连接和上下文

  在web.config中添加数据库链接

<connectionStrings>
    <add name="EfDefault" connectionString="Server=.;Database=CodeFirstApp;Integrated Security=SSPI" providerName="System.Data.SqlClient"/>
  </connectionStrings>

  创建上下文EfContext

public class EfContext : DbContext
    {
        public EfContext():base("name=EfDefault")
        {
            
        }

        private DbSet<Student> Students { get; set; } 
    }

  在这里,DbContext是所有基于EF的上下文基类,通过它可以访问到数据库中的所有表。上面的代码中调用了父类的构造函数,并且传入了一个键值对,键是name,值是FirstCodeFirstApp

五、启用迁移

  在程序包管理器控制台用命令进行开启迁移

PM> Enable-Migrations

  a.指定DbContext: Enable-Migrations -ContextTypeName XXXXContext

  b.指定项目名称:      Enable-Migrations -StartUpProjectName XXX -Force

  将自动生成迁移文件夹Migrations和Configuration.cs

namespace EntityFrameworkExtension.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<EntityFrameworkExtension.Entities.EfContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(EntityFrameworkExtension.Entities.EfContext 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.
        }
    }
}

  这时自动迁移是被关闭的,需要手动迁移

PM> add-migration InitDb

  将自动在Migrations生成迁移代码文件xxxx_迁移名称.cs,如201804160820076_InitDb.cs

  使用命令进行手动迁移

PM> update-database -verbose

  verbose可以查看命令的执行过程

Using StartUp project 'EntityFrameworkExtension'.
Using NuGet project 'EntityFrameworkExtension'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'CodeFirstApp' (DataSource: ., Provider: System.Data.SqlClient, Origin: Configuration).
Applying explicit migrations: [201804160820076_InitDb].
Applying explicit migration: 201804160820076_InitDb.
CREATE TABLE [dbo].[Students] (
    [Id] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](max),
    [Age] [int] NOT NULL,
    CONSTRAINT [PK_dbo.Students] PRIMARY KEY ([Id])
)
CREATE TABLE [dbo].[__MigrationHistory] (
    [MigrationId] [nvarchar](150) NOT NULL,
    [ContextKey] [nvarchar](300) NOT NULL,
    [Model] [varbinary](max) NOT NULL,
    [ProductVersion] [nvarchar](32) NOT NULL,
    CONSTRAINT [PK_dbo.__MigrationHistory] PRIMARY KEY ([MigrationId], [ContextKey])
)
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201804160820076_InitDb', N'EntityFrameworkExtension.Migrations.Configuration',  此处省略  , N'6.2.0-61023')

Running Seed method.

然后刷新数据库即可看到创建的表,其中__MigrationHistory是EF自动生成的迁移日志表

六、生成指定版本的迁移脚本

PM> Update-Database -SourceMigration 201806190702572_XX1 -TargetMigration 201806200143418_XX2 -Script 

生成迁移脚本时产生错误:
  未能找到任何适合于指定的区域性或非特定区域性的资源。请确保在编译时已将“MMIS.Data.Migrations.AlterReceive.resources”正确嵌入或链接到程序集“MMIS.Data”,或者确保所有需要的附属程序集都可加载并已进行了完全签名。

原因:

  Migrations迁移文件夹下的每个迁移文件包含xxxx.cs、xxxx.Designer.cs、xxxx.resx,而其中.resx文件由于svn的原因而被隐藏导致的

 

 

 迁移问题总结

 一、当前库的数据库表结构已被更改为最新,出现未迁移提醒的问题。

   可能的起因:两个人都提交了迁移文件,进行一次update-database,引起迁移冲突

  解决:

  删除迁移表的本次迁移记录(多条),删除迁移文件(多个)。

  重新使用Add-Migration AddNewTest生成迁移文件,注释掉迁移文件内容,进行update-database -verbose

 

 

 参考文章:http://www.cnblogs.com/farb/p/FirstCodeFirstApp.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值