code first 数据库创建更新

通过下面的例子我遇到了些许问题。
1.生成数据库后找不到数据库到底在哪
2.用mvc4生成数据库后,手动删除数据库后,没有办法从新生成数据库Cannot attach the file as database shit。

第一个问题:
找到连接字符串

string x=((IObjectContextAdapter)db).ObjectContext.Connection.ConnectionString;

找到之后就可以查看了。
第二个问题:无解,试了很多方法都没有办法。唯一的办法就是进入到vs的服务器资源管理器中找到数据库连接,分离数据库在删除。就行了

所以最好在修改数据库的时候不删除原数据库而是通过使用Migrations的方法更改数据库
该方法的使用过程如下
1.创建一个console程序或者MVC4空程序。
2.添加entityframework
Tools –> Library Package Manager –> Package Manager Console 然后键入Install-Package EntityFramework 获取最新entityframework(mvc支持到entityframework 5所以 使用Install-Package EntityFramework -version 5.0 添加,版本为4.4.0.0)
3.激活迁移(migration)
键入Enable-Migrations 来激活迁移方案。自动创建Migrations 文件夹和两个文件The Configuration class,An InitialCreate migration
4.修改model。
5.添加迁移方案 键入 Add-Migration 迁移名 然后更新数据库 Update-DatabaseUpdate-Database –Verbose(可以看到sql)

其他1.回滚到以前的迁移 Update-Database –TargetMigration: $InitialDatabase
其他2.使用SQL script进行迁移 Update-Database -script
其他3.使用SQL script定向迁移Update-Database -Script -SourceMigration: $InitialDatabase -TargetMigration: AddPostAbstract

以下为例子
Building an Initial Model & Database

Before we start using migrations we need a project and a Code First model to work with. For this walkthrough we are going to use the canonical Blog and Post model.

Create a new MigrationsDemo Console application
Add the latest version of the EntityFramework NuGet package to the project
Tools –> Library Package Manager –> Package Manager Console
Run the Install-Package EntityFramework command
Add a Model.cs file with the code shown below. This code defines a single Blog class that makes up our domain model and a BlogContext class that is our EF Code First context
using System.Data.Entity;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Infrastructure;

namespace MigrationsDemo 
{ 
    public class BlogContext : DbContext 
    { 
        public DbSet<Blog> Blogs { get; set; } 
    } 

    public class Blog 
    { 
        public int BlogId { get; set; } 
        public string Name { get; set; } 
    } 
}

Now that we have a model it’s time to use it to perform data access. Update the Program.cs file with the code shown below.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace MigrationsDemo 
{
    
    class Program 
    {
    
        static void Main(string[] args) 
        { 
            using (var db = new BlogContext()) 
            { 
                db.Blogs.Add(new Blog { Name = "Another Blog " }); 
                db.SaveChanges(); 

                foreach (var blog in db.Blogs) 
                { 
                    Console.WriteLine(blog.Name); 
                } 
            } 

            Console.WriteLine("Press any key to exit..."); 
            Console.ReadKey(); 
        } 
    } 
}

Run your application and you will see that a MigrationsCodeDemo.BlogContext database is created for you.

If SQL Express is installed (included in Visual Studio 2010) then the database is created on your local SQL Express instance (.\SQLEXPRESS). If SQL Express is not installed then Code First will try and use LocalDb ((localdb)\v11.0) - LocalDb is included with Visual Studio 2012.

Note: SQL Express will always get precedence if it is installed, even if you are using Visual Studio 2012

//实际上在这里我生成的为
Data Source=(localdb)\mssqllocaldb;
Integrated Security=True;
Connect Timeout=15;
Encrypt=False;
TrustServerCertificate=False

//而不是 
Data Source=(localdb)\ProjectsV12;
Initial Catalog=master;
Integrated Security=True;
Connect Timeout=30;
Encrypt=False;
TrustServerCertificate=False

所以我们我们需要重新连接才能看到他。这就是问题,要找到这个连接字符串我们需要使用

string x = ((IObjectContextAdapter)db).ObjectContext.Connection.ConnectionString;

来找到这个字符串。

(LocaDb Database)
这里写图片描述

(SQL Express Database)
这里写图片描述

Enabling Migrations

It’s time to make some more changes to our model.

Let’s introduce a Url property to the Blog class.
public string Url { get; set; }
If you were to run the application again you would get an InvalidOperationException stating The model backing the ‘BlogContext’ context has changed since the database was created. Consider using Code First Migrations to update the database ( http://go.microsoft.com/fwlink/?LinkId=238269).

As the exception suggests, it’s time to start using Code First Migrations. The first step is to enable migrations for our context.

Run the Enable-Migrations command in Package Manager Console
This command has added a Migrations folder to our project, this new folder contains two files:

The Configuration class. This class allows you to configure how Migrations behaves for your context. For this walkthrough we will just use the default configuration.
Because there is just a single Code First context in your project, Enable-Migrations has automatically filled in the context type this configuration applies to.
An InitialCreate migration. This migration was generated because we already had Code First create a database for us, before we enabled migrations. The code in this scaffolded migration represents the objects that have already been created in the database. In our case that is the Blog table with a BlogId and Name columns. The filename includes a timestamp to help with ordering.
If the database had not already been created this InitialCreate migration would not have been added to the project. Instead, the first time we call Add-Migration the code to create these tables would be scaffolded to a new migration.
Multiple Models Targeting the Same Database

When using versions prior to EF6, only one Code First model could be used to generate/manage the schema of a database. This is the result of a single __MigrationsHistory table per database with no way to identify which entries belong to which model.

Starting with EF6, the Configuration class includes a ContextKey property. This acts as a unique identifier for each Code First model. A corresponding column in the __MigrationsHistory table allows entries from multiple models to share the table. By default, this property is set to the fully qualified name of your context.

Generating & Running Migrations

Code First Migrations has two primary commands that you are going to become familiar with.

Add-Migration will scaffold the next migration based on changes you have made to your m

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值