zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    R安装程序包:ERROR: failed to lock directory ‘/usr/lib64/R/library’ for modifying
    clusterProfiler
    R 画图保存为文件
    网站支持https之一:https原理和SSL证书类型
    Https系列之一:https的简单介绍及SSL证书的生成
    What is the difference between a directory and a folder?
    漫画解读:通过造车来了解软件开发模式 DevOps
    Multicast delegate of type Func (with return value)?
    What are good ways to prevent SQL injection? [duplicate]
    SqlCommand.Prepare Method
  • 原文地址:https://www.cnblogs.com/xcsn/p/8856605.html
Copyright © 2011-2022 走看看