如果在Code First模式下使用,使用T4模板为Database First和Model First开发生成的代码可能无法正常工作

我在我的asp.net MVC 4应用程序中使用entity framework工作。 我有一个edmx文件。 我试图使用这个EF模型中的实体来填充像这样的视图模型:

using (var context = new VehiclesContext()) { IEnumerable 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); } 

Vehicle是edmx中的实体,其中SearchedVehicles是viewmodel但是我得到了这个exception:

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

这是每个设计。 您已经从数据库创建了一个模型,表明您的代码永远不应该创建数据库。

您收到的错误消息是因为它找不到数据库而因此尝试创建它。

要解决此问题,您需要检查您的connectionstring以确保它可以找到您要连接的数据库。 如果你真的想要创建数据库,你应该先找代码。 这意味着要么删除“抛出新exception”行并继续使用模型(这意味着您不能再从数据库更新模型,因为它会重新插入exception行),或者您可以将数据库反向工程为代码 – 第一个模型。

有关逆向工程技巧,请参阅http://msdn.microsoft.com/en-us/data/jj593170.aspx 。

我有同样的错误’使用T4模板生成的代码……’。 我的问题与上述不同。 我的数据库表架构已更改。 因此,在刷新之后,我通过将其打开为xml(rt单击并打开Open With …并选择xml)来编辑edmx。 修复xml中的所有错误后,当我运行应用程序时,我得到上述错误。 因此,下次我在TFS中撤消所有内容,并继续从Edmx图表页面中删除并添加有问题的表格。 这样做有助于解决上述错误。 还学到了,永远不要在xml模式下编辑edmx文件。

快乐的编码。