MVC4 - 控制器脚手架,自定义数据上下文类问题:无法检索元数据

时间:2014-04-21 20:30:28

标签: asp.net-mvc-4 datacontext asp.net-mvc-scaffolding

当我尝试通过脚手架创建控制器时,出现以下错误:

无法检索“TurkUp.Models.Admin.CreateCourseViewModel”的元数据。指定的架构无效。错误: CLR类型EDM的映射是不明确的,因为多个CLR类型与EDM类型“课程作业”匹配。

以下是该模型的代码:

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace TorkUp.Models.Admin
{
    public class CreateCourseViewModel
    {
        [HiddenInput(DisplayValue = false)]
        public int Id { get; set; }

        [Required]
        public string Title { get; set; }
    }
}

自定义数据上下文类:

using System.Data.Entity;
using System.Linq;
using TorkUp.ClassLibrary;
using TorkUp.ClassLibrary.Admin;
using TorkUp.ClassLibrary.User;

namespace TorkUp.Infrastructure
{
    public class UniversityDb : DbContext, IUniversityDataSource
    {
        public UniversityDb() : base("DefaultConnection") { }

        // Admin data
        public DbSet<Course> Courses { get; set; }
        public DbSet<Class> Classes { get; set; }
        public DbSet<Coursework> Courseworks { get; set; }
        public DbSet<Student> Students { get; set; }

        // User data
        public DbSet<Assignment> Assignments { get; set; }
        public DbSet<Task> Tasks { get; set; }


        // Admin data
        IQueryable<Course> IUniversityDataSource.Courses { get { return Courses; } }

        IQueryable<Class> IUniversityDataSource.Classes { get { return Classes; } }

        IQueryable<Coursework> IUniversityDataSource.Courseworks { get { return Courseworks; } }

        IQueryable<Student> IUniversityDataSource.Students { get { return Students; } }

        // User data
        IQueryable<Assignment> IUniversityDataSource.Assignments { get { return Assignments; } }
        IQueryable<Task> IUniversityDataSource.Tasks { get { return Tasks; } }

        // Save to database
        void IUniversityDataSource.Save() { SaveChanges(); }
    }
}

课程的课程:

using System.Collections.Generic;

namespace TorkUp.ClassLibrary.Admin
{
    public class Course
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public ICollection<Class> Classes { get; set; }
        public ICollection<Coursework> Courseworks { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

如果您有此错误,那是因为DbContext

   // Admin data
    public DbSet<Course> Courses { get; set; }
    public DbSet<Class> Classes { get; set; }
    public DbSet<Coursework> Courseworks { get; set; } //you use here Coursework class to create a DbSet. But when you scaffold you use CreateCourseViewModel.
    public DbSet<Student> Students { get; set; }

如果您想使用CreateCourseViewModel,则必须更改上面的这一行。但是我认为,当您放置ViewModel后缀时,CreatecourseViewModel的目的是包装另一个类以便在视图中显示。