我在我的asp.net MVC 4應用程序中使用實體框架工作。我有一個edmx文件。我試圖使用實體從這個EF模型來填充這樣的視圖模型:如果在代碼優先模式下使用T4模板for Database First和Model First開發生成的代碼可能無法正常工作
using (var context = new VehiclesContext())
{
IEnumerable<SearchedVehicles> vehicles = context.Vehicles.Select(x => new SearchedVehicles
{
Year = x.Year,
Make = x.Make,
Model = x.Model,
Mileage = x.Mileage,
VIN = x.VIN
});
return View(vehicles);
}
車輛是在EDMX其中SearchedVehicles是視圖模型實體,但我得到這個異常:
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();
}
我沒有看到app.config文件中的任何連接字符串(edmx是在類庫項目中)我應該在app.config中添加連接字符串還是在使用此edmx的web.config中添加連接字符串?另外,當我創建edmx時,爲什麼沒有在app.config中創建連接字符串 – DotnetSparrow
web.config是您的Web應用程序使用的。但奇怪的是它沒有爲你生成一個連接字符串...... – Zaphod
如果你使用model-first(從數據庫生成模型)並且通過一個額外的構造函數指定一個顯式連接字符串,確保你使用正確的連接字符串樣式,即通過[這裏](http://stackoverflow.com/a/5942978/845584)。 – PeterX