Creating a Database for Getting Started with EF Codefirst

  The experimental environment is VS 2015, MSSQL Server 2008, windows 10

1. Create a project

  Create an MVC5 project EntityFrameworkExtension through VS

2. Install Entity Framework

  Add Entity Framework to the project via nuget, the current version is 6.2.0

3. Create the entity class Student  

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

    }

Fourth, add database connection and context

  Add database link in web.config

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

  Create context EfContext

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

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

  Here, DbContext is the base class for all EF-based contexts, through which all tables in the database can be accessed. The above code calls the constructor of the parent class, and passes in a key-value pair, the key is name, and the value is FirstCodeFirstApp

5. Enable Migration

  Start the migration with the command in the package manager console

PM> Enable-Migrations

  Migration folders Migrations and Configuration.cs will be automatically generated

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.
        }
    }
}

  At this time, automatic migration is turned off and manual migration is required.

PM> add-migration InitDb

  The migration code file xxxx_migration name.cs will be automatically generated in Migrations, such as 201804160820076_InitDb.cs

  Manual migration using command

PM> update-database -verbose

  Verbose can view the execution process of the command

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 ' , omitted here, N ' 6.2.0-61023 ' )

Running Seed method.

Then refresh the database to see the created table, where __MigrationHistory is the migration log table automatically generated by EF

 

 

 

 Reference article: http://www.cnblogs.com/farb/p/FirstCodeFirstApp.html

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324521387&siteId=291194637