22

我放棄了。 我發現這個: http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx 並認爲,這很酷。 所以我很快重新設計了我的模型,以充分利用兩個世界中的最好的一個。模型首先用DbContext,未能初始化新的數據庫

但是現在我的模型在創建新的數據庫時失敗(或者將tabls添加到現有的數據庫中)。 我得到這個錯誤:

Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.

在:

 protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     throw new UnintentionalCodeFirstException(); 
    } 

這就是我的連接字符串:

<add name="ForumContextContainer" 
providerName="System.Data.SqlClient" 
connectionString="Data Source=.\SQLExpress; Initial Catalog=iForum; Integrated Security=True"/> 

注意。我稍後添加了初始目錄,嘗試它是否能夠正常工作,但它完全一樣。

回答

32

這是錯誤的連接字符串。一旦你使用了model-first/database-first(EDMX),你必須使用Entity connection string來引用.ssdl,.msl和.csdl元數據文件。另外請注意,從EDMX =創建模型時,您必須在設計時創建數據庫=您必須生成SQL腳本並執行它以創建數據庫。

+0

其實我通過chaning T4模板找到了一種方法。但是,無論如何, – 2011-05-09 22:24:12

+14

@ŁukaszBaran很在意分享您的解決方案嗎? – 2011-07-28 20:25:22

+0

@JoelBeckham我的問題是拋出新的UnintentionalCodeFirstException();在Entities類中。 – Saber 2012-02-14 09:12:23

2

我想這個錯誤通常出現在有人將EDMX/db首先添加到解決方案中的類庫中時。如果你這樣做,請確保在類庫項目中的App.config文件中添加的連接字符串在web.config或exe項目配置文件中可用(只需在其中複製/粘貼)。

+0

當所有其他人都失敗時,這個簡單的解決方案對我有用。只需將模型dll項目中的app.config中的連接字符串部分複製到MVC應用程序web.config。 – Thronk 2013-12-06 18:18:59

0
Add this connection string to web config and make changes: 

<add name="Entities" 
connectionString=" 
metadata=res://*/EFmodel.csdl|res://*/EFmodel.ssdl|res://*/EFmodel.msl; 
provider=System.Data.SqlClient;provider 
connection string=&quot; 
data source=SAI-PC; 
initial catalog=OrderDB; 
user id=sa; 
password=Pass$123; 
MultipleActiveResultSets=True; 
App=EntityFramework&quot;" 
providerName="System.Data.EntityClient" /> 

EFmodel is my .edmx file name. 

OrderDB is database name. 
-1

刪除或發表評論的:

//protected override void OnModelCreating(DbModelBuilder modelBuilder) 
//{ 
// throw new UnintentionalCodeFirstException(); 
//} 

,改變你的連接字符串,有效的。