【问题标题】:Scaffolding with Entity Framework in ASP.NET MVC 4在 ASP.NET MVC 4 中使用实体框架搭建脚手架
【发布时间】:2013-01-04 18:04:05
【问题描述】:

我正在关注“Professional ASP.NET MVC 4”并尝试使用实体框架从模型生成控制器。我的模型如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MvcMusicStore.Models
{
    public class MusicStoreModels
    {
        public class Album
        {
            public virtual int AlbumId { get; set; }
            public virtual int GenreId { get; set; }
            public virtual int ArtistId { get; set; }
            public virtual string Title { get; set; }
            public virtual decimal Price { get; set; }
            public virtual string AlbumArtUrl { get; set; }
            public virtual Genre Genre { get; set; }
            public virtual Artist Artist { get; set; }
        }

        public class Artist
        {
            public virtual int ArtistId { get; set; }
            public virtual string Name { get; set; }
        }

        public class Genre
        {
            public virtual int GenreId { get; set; }
            public virtual string Name { get; set; }
            public virtual string Description { get; set; }
            public virtual List<Album> Albums { get; set; }
        }
    }
}

当我右键单击我的 Controllers 文件夹并选择 Add > Controller 我选择 “具有读/写操作和视图的 MVC 控制器,使用实体框架” 作为我的模板,"Album (MvcMusicStore.Models)" 作为我的模型类。这本书告诉我选择“新数据上下文...”并将其命名为“MvcMusicStore.Models.MusicStoreDBContext”

一切看起来都不错,在执行上述操作之前,我已经保存并构建了我的解决方案。但是,我收到一条错误消息说

There was an error generating 'MvcMusicStore.Models.MusicStoreDBContext'.
Try rebuilding your project.'

我有点不知所措。有人可以帮忙吗?

【问题讨论】:

  • 为什么每个属性都是virtual
  • 老实说,我不知道。引用这本书:“你可能还注意到每个属性都是虚拟的。我将在本章后面讨论为什么属性是虚拟的。现在,这三个简单的类定义是你的起始模型,包括你需要搭建一个控制器和一些视图,甚至创建一个数据库。”
  • virtual 属性有助于延迟加载实体。
  • 我已经在 Visual Studio 2012 中通过 NuGet 安装了 Entity Framework 5,但是当我尝试生成我的控制器时仍然遇到同样的问题。我是否在某处遗漏了 using 语句?感觉很沮丧。
  • 我不会将原始属性(int、string、decimal)作为虚拟属性,延迟加载它们没有意义。

标签: asp.net entity-framework asp.net-mvc-4


【解决方案1】:

症状听起来很像这个问题: http://www.rhysgodfrey.co.uk/archive/2011/04/20/mvc3-tools-update-and-entity-framework-4-1-error.aspx

我建议卸载所有版本的 Entity Framework,通过 NuGet 重新安装最新版本,然后从头开始重新生成 EF 上下文。

【讨论】:

    【解决方案2】:

    我不太喜欢 C#(我认为这是 C# 代码 - 但不要引用我的话).....

    在将您的代码粘贴到一个新项目中之后,我注意到上面写着

    的行
    Using System.Data.Entity;
    

    被标记为错误, 一些进一步的研究表明,您的 config.sys 文件中可能缺少引用...

    回复:http://forums.asp.net/t/1381740.aspx/1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      相关资源
      最近更新 更多