EF代码第一现有数据库 [英] EF Code First Existing database

查看:100
本文介绍了EF代码第一现有数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先使用EF 4.1代码,我想停止从模型创建数据库的EF。据了解,如果您传递Connectionstring名称,它将使用该连接字符串的现有数据库。但是如果数据库不存在,那么它将创建数据库,所有表都将构成模型。

Using EF 4.1 Code first I wanted to stop EF creating database from Models. As I understand if you pass Connectionstring name it will use existing database from that connection string. However if the database does not exists then it will create database will all the tables form the model.

  <connectionStrings>
<add name="DiaryContext" connectionString="Data Source=.;Initial Catalog=Diary;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>

        public MyDiaryContext() : 
        base("name=DiaryContext")
    {
        this.Configuration.LazyLoadingEnabled = true;
        this.Configuration.ProxyCreationEnabled = false;
    }

在上面的例子中,它的行为如下:

In the above example its behaving as follows:

(1)如果数据库不存在,那么它将创建具有所有表的数据库等。

(1) if database does not exists then it will create the database with all the tables etc.

(2)如果数据库存在并且它没有表,那么它不会创建新的表

(2) if the database exists and it has no tables then it will not create new tables

(3)如果我添加新的模型EF代码,那么它不会在数据库中创建新的表。

(3) if I add new model the EF code then it will not create the new table in the database.

我对2和3感到满意,但是在(1)如果数据库不存在的情况下,我希望它抛出异常而不是创建数据库和表。

I am happy with 2 and 3 but in case of (1) if database does not exists then I wanted it to throw the exception instead of creating the db and tables.

在我的情况下,数据库是由DBA管理的,我没有完全控制这个。

In my case the database is being managed by DBA and I dont have total control over this.

任何人都有任何想法如何解决这个问题?

Does anyone have any idea how to achive this?

非常感谢,

推荐答案

p>首先使用EF代码时,您需要设置一个DB Initializer I,例如在DataContext的构造函数中执行此操作。

When you use EF Code first you need to set a DB Initializer I for example do this in the constructor of my DataContext

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<WebContext>());

有一些默认的隐含,如DropCreateDatabaseIfModelChanges和DropCreateDatabaseAlways可以使用。然而,如果您没有任何数据库或表生成,只需确保没有设置或继承初始化程序,并且可以对现有数据库使用该模型。良好的文章 by scot gu

There are a few default implmentations like DropCreateDatabaseIfModelChanges and DropCreateDatabaseAlways you can use. If however you don't wont any DB or tables generate just make sure that no Initializer is being set or inherited from and you can use the model against an existing db. Good article by scot gu

这篇关于EF代码第一现有数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆