如果在代码优先模式下使用,则使用用于数据库优先和模型优先开发的 T4 模板生成的代码可能无法正常工作



我在 asp.net MVC 4应用程序中使用实体框架工作。我有一个 edmx 文件。我正在尝试使用此 EF 模型中的实体来填充如下所示的视图模型:

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 中的实体,其中搜索车辆是视图模型,但我得到这个异常:

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

这是每个设计。您已从数据库创建了一个模型,这指示您的代码不应创建数据库。

出现错误消息是因为它找不到数据库,因此尝试创建数据库。

若要解决此问题,需要检查连接字符串,以确保它可以找到要连接到的数据库。如果你真的想创建数据库,你应该先去写代码。这意味着要么删除"抛出新异常"行并继续使用该模型(这意味着您不能再从数据库更新模型,因为它会重新插入异常行),或者您可以将数据库逆向工程为代码优先模型。

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

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

快乐编码。

相关内容

最新更新