开发者

EF Code First Existing database

Using EF 4.1 开发者_Go百科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) if database does not exists then it will create the database with all the tables etc.

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

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

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.

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?

Many thanks,


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>());

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜