ocdefirst安装更新数据库

数据迁移(Migrations)

启用数据迁移
在控制台中输入如下命令:Enable-Migrations


这时会在项目目录中增加一个Migrations文件夹,里面放置了两个文件:
EF会通过C#代码的方式将每一次对模型的修改保存到这个文件夹中


每个迁移文件,都包含Up和Down两个重写函数,分别对应于更新和回退。
上面的代码也很直白,Up函数中创建一个Students表,定义表结构并指定ID主键(PrimaryKey),Down函数用来回退操作,里面简单的删除了Students表。

EF会在数据库中自动生成一个名为__MigrationHistory表来跟踪数据库的状态。

增加迁移项需要我们手工来进行,在程序包管理器控制台中,输入如下命令:
Add-Migration Add_Annotation_Name_Major(名字)


时会在Migrations目录下生成迁移文件,文件是以[时间+迁移名]命名的,方便查找:
201612160406415_Add_Annotation_Name_Major.cs

更新到数据库
此时,数据库尚未改变,我们还需要手工命令来更新数据库:
Update-Database

在真实的项目中,数据库可能部署在远程服务器中,这时我们就不能直接在VS中通过Update-Database来更新数据库了。
不过我们可以生成更新SQL脚本,然后拿到数据库服务器上执行。生成这个SQL脚本的方法:
Update-Database ? -Script
-SourceMigration: InitialCreate
-TargetMigration: Add_Annotation_Name_Major


安装EF
工具----库程序包管理器---程序包管理器控制台
在下方鼠标闪动的地方输入:Install-Package EntityFramework 然后回车,安装成功出现“已成功将“EntityFramework 6.1.3”添加到 MVC+EFBoKeYu。”字样

PM> Install-Package EntityFramework
已成功安装“EntityFramework 5.0.0”。
已成功将“EntityFramework 5.0.0”添加到 EFDemo。
Type 'get-help EntityFramework' to see all available Entity Framework commands.

安装后的变化
上述操作执行完毕后,会发现项目变化
1.新增了一个packages.config文件


PM> enable-migrations
会生成Migrations
AutomaticMigrationsEnabled = true;设为true

然后在添加字段里的那个类 写好要添加的字段,默认项目一定要选对,选对!!!!!!!!!
这里的添加是与数据库同步的,改后要加Add-Migration xxx Update-Database

无论你是添加的了字段还是删除了字段,
第一步都是PM> Add-Migration 添加了username字段
第二步是 PM> Update-Database
刷新数据库,就会看到一些字段就没了

Enable-Migrations 这个命令将在项目下创建文件夹 Migrations

生成、运行迁移

  Code First Migrations 有两个你需要熟悉的命令:

Add-Migration 将 scaffold 创建下一次基于上一次迁移以来的更改的迁移;
Update-Databse 将任何挂起的迁移应用到数据库

PM> Add-Migration 添加了username字段
Scaffolding migration '添加了username字段'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration 添加了username字段' again.
PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201707081019084_添加了username字段].
Applying explicit migration: 201707081019084_添加了username字段.
Running Seed method.

PM> Add-Migration xxx
Scaffolding migration 'xxx'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration xxx' again.
PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201707081021323_xxx].
Applying explicit migration: 201707081021323_xxx.
Running Seed method.
-----------------------------------------------------------------------------------------------------------------------------------

使用CodeFirst的约定连接并指定数据库名称
如果在应用程序中没有做任何配置,那么调用构造函数时,可以给它一个string类型的参数,这样将建立一个以该参数为名字的数据库。例如:

public class BloggingContext : DbContext
{
public BloggingContext(): base("BloggingDatabase")
{
}
}

例子中将在SQL Express或者LocalDb中创建名称为"BloggingDatabase"的数据库。同样,如果SQL Express和LocalDb都安装的话,那么EF会选择在SQL Express中创建数据库。

使用CodeFirst及配置文件中的connection string
你也可以选择先先在配置文件中设置好connection string。例如:

<configuration>
<connectionStrings>
<add name="BloggingCompactDatabase"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=Blogging.sdf"/>
</connectionStrings>
</configuration>

然后,创建数据库上下文时使用下面的代码:

public class BloggingContext : DbContext
{
public BloggingContext(): base("BloggingCompactDatabase")
{
}
}

此时,创建数据库时,就会使用ConnectionString中指定的服务器和数据库名字。

你会发现这里创建数据库上下文的代码与上一节的非常相似,除了参数名字不一样。事实上,上面一段代码执行的时候,EF首先查找配置文件中有没有以“BloggingCompactDataBase”命名的连接字符串,如果有则使用该连接字符串,连接数据库(数据库未创建时会自动创建)。如果没有,那么会在SQLExpress或者LocalDb中名创建数名为“BloggingCompactDataBase”的数据库。

或者,也可以用“name=<connection string name>” 作为基类DbContext的构造函数的参数。例如:

public class BloggingContext : DbContext
{
public BloggingContext()
: base("name=BloggingCompactDatabase")
{
}

//下面的必不可少  映射
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

}


}

注意:这种形式明确说明需要在配置文件中找到名字为“BloggingCompactDataBase”的连接字符串,如果没有找到,则会抛出异常。
------------------------------------------------------------------------------------------------------------------------
使用Database/Model First 及配置文件中的连接字符串
ModelFirst与CodeFirst不同,Models通过EF设计器创建,Models通常以EMDX文件的存在。

设计器会添加一个EF连接字符串到配置文件中。这个连接字符串比较特殊,它包括怎样从EDMX文件中获取信息。例如:

<configuration>
<connectionStrings>
<add name="Northwind_Entities"
connectionString="metadata=res://*/Northwind.csdl|
res://*/Northwind.ssdl|
res://*/Northwind.msl;
provider=System.Data.SqlClient;
provider connection string=
&quot;Data Source=.sqlexpress;
Initial Catalog=Northwind;
Integrated Security=True;
MultipleActiveResultSets=True&quot;"
providerName="System.Data.EntityClient"/>
</connectionStrings>
</configuration>

EF设计器会生成下面的代码,其中通过传递连接字符串的名字来告诉DbContext使用这个连接字符串。

public class NorthwindContext : DbContext
{
public NorthwindContext()
: base("name=Northwind_Entities")
{
}
}

DbContext就会装入已经存在的model,而不是使用CodeFirst从code中计算,因为连接字符串是一个EF Connection string,其中包含了使用的model的细节。

原文地址:https://www.cnblogs.com/ZkbFighting/p/8306104.html