asp.net-mvc - 带有继承的 MVC 5 脚手架使用了错误的实体集

标签 asp.net-mvc entity-framework asp.net-mvc-5 dbcontext entity-framework-6.1

在 MVC 5 和 EF 6.1 中,我使用简单的继承层次结构,其中 Student 类继承自 Person 类。对于这两个类,我的数据库上下文中有一个实体集(DbSet 属性):

public class DatabaseContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public DbSet<Student> Students { get; set; }
}

现在,当我要求脚手架为子类 Student 生成 Controller 时,它使用 Persons 实体集,导致诸如这样的语句

    Student student = db.Persons.Find(id);

编译器显然提示它不能将任何 Person 转换为 Student。

有没有办法确保脚手架使用正确的实体集(在本例中为学生)?

请注意,删除 Persons 实体集并不是一个好的解决方案,因为还有其他 Controller 需要它。

最佳答案

使用查找和替换将父 DBSet 的 Controller 类中的所有匹配项更改为子 DBSet,例如将 Persons 更改为 Students。

正如您可能知道的那样(我认为您提出了这一点)Microsoft 已确认这是一个已知错误 http://connect.microsoft.com/VisualStudio/feedbackdetail/view/945937/mvc-5-scaffolding-with-inheritance-uses-the-wrong-entity-set但他们不会修复它。

关于asp.net-mvc - 带有继承的 MVC 5 脚手架使用了错误的实体集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25075655/

相关文章:

asp.net-mvc - "processing"错误消息将 MVC4 部署到 Elastic Beanstalk

c# - 映射自定义路由 ASP.NET MVC5

c# - ASP.NET MVC网站从磁盘读取文件问题

c# - 从 ASP.Net Core 1.1 迁移到 2.0 时出现 BadImageFormatException

c# - 使用 Effort.EF6 测试预加载场景

c# - 为什么我在 ApplicationUser 中的自定义对象属性为空?

asp.net-mvc - 如何使用 ASP.NET MVC 5 应用程序将文件上传到第三个 API 服务?

c# - 在 asp.net MVC6 View 中删除 if 语句的最佳方法

asp.net-mvc - 将 Sql Server CE 4.0 部署到 IIS 7 时出现问题

c# - DataContext 始终返回 null 作为外键