0

I previously had the following line of code from within my AdminController that was successfully returning a list of relevant subsections from within a course:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCourseSections(int courseID)
{ 
  var Sections = dbcontext.CourseSection.Where(cs => cs.CourseID.Equals(courseID)).Select(x => new
  {            
    sectionID = x.CourseSectionID,
    sectionTitle = x.Title
  );
  return Json(Sections, JsonRequestBehavior.AllowGet);
}

I was informed to take this out of the controller as it was bad practice to call dbcontext and so i moved this to the AdminViewModel. Within my AdminViewModel I have a variable public List CourseSectionList { get; set; } and I am trying to populate this variable with the JSON request details. My code is as follows:

AdminViewModel

public void GetCourseSectionDetails(int courseID)
{
  var Sections = dbcontext.CourseSection.Where(cs => cs.CourseID.Equals(courseID)).Select(x => new CourseSection
  {
    CourseSectionID = x.CourseSectionID,
    Title = x.Title
  });
  this.CourseSectionList = Sections.ToList();
}

AdminController

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCourseSections(int courseID)
{ 
  avm.GetCourseSectionDetails(courseID);
  var Sections = avm.CourseSectionList.Where(cs => cs.CourseID.Equals(courseID)).Select(x => new
  {            
    sectionID = x.CourseSectionID,
    sectionTitle = x.Title
  });
  System.Diagnostics.EventLog.WriteEntry("Application", "JSON=" + Sections.ToList(), System.Diagnostics.EventLogEntryType.Error);
  return Json(Sections, JsonRequestBehavior.AllowGet);
}

I am getting the error The entity or complex type 'MetaLearning.Data.CourseSection' cannot be constructed in a LINQ to Entities query. How can I populate this.CourseSectionList variable using the Sections?

4

3 回答 3

2

正如您的错误消息所指出的,您不能在 inlinq to entities中使用

.Select(m => new <Entity>{bla bla})

其中<Entity>... 是模型的实体之一。

因此,您要么使用具有所需属性的“非模型”类(DTO),要么在选择之前必须枚举(因为linq to objects没有那个限制)

.ToList()
.Select(m => new <Entity>{bla bla});

你可以在这里找到一些很好的解释为什么它不可能

编辑 :

如果您只想检索实体的某些属性,并且不想使用 DTO,您也可以这样做:

return ctx
        .CourseSection
         .Where(cs => cs.CourseID.Equals(courseID))
         //use an anonymous object to retrieve only the wanted properties
         .Select(x => new 
                {
                    c= x.CourseSectionID,
                    t= x.Title,
                })
         //enumerate, good bye linq2entities
         .ToList()
         //welcome to linq2objects
         .Select(m => new CourseSection {
                     CourseSectionID = m.c,
                     Title = m.t,
          })
          .ToList();
于 2013-08-21T16:56:00.340 回答
0

您不需要在控制器中重复相同的代码,而是直接将列表传递给视图。

话虽如此,我是在通知您,将数据访问代码放在您的视图模型中比将其保存在控制器中更糟糕。我建议你有一个特定的 DAL 层:

public interface IRepository
{
    public IList<CourseSection> GetSections(int courseID);
}

这将被实施:

public class RepositoryEF : IRepository
{
    public IList<CourseSection> GetSections(int courseID)
    {
        using (ctx = new YourDbContextHere())
        {
            return ctx
                .CourseSection
                .Where(cs => cs.CourseID.Equals(courseID))
                .Select(x => new CourseSection
                {
                    CourseSectionID = x.CourseSectionID,
                    Title = x.Title,
                })
                .ToList();
        }
    }
}

最后让您的控制器将存储库作为依赖项:

public class SomeController : Controller
{
    private readonly IRepository repo;
    public SomeController(IRepository repo)
    {
        this.repo = repo;
    }

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult GetCourseSections(int courseID)
    { 
        var sections = this.repo.GetSections(courseID);
        return Json(sections, JsonRequestBehavior.AllowGet);
    }
}
于 2013-08-21T16:20:28.450 回答
0

我使用 Darin 的回答作为指导,按以下方式执行此操作:

视图模型

public void GetCourseSectionDetails(int courseID)
    {
        this.CourseSectionList = dbcontext.CourseSection.AsEnumerable().Where(cs => cs.CourseID.Equals(courseID)).Select(x => new CourseSection
        {
            CourseSectionID = x.CourseSectionID,
            Title = x.Title
        }).ToList();
    }

控制器

[AcceptVerbs(HttpVerbs.Get)]
    public JsonResult GetCourseSections(int courseID)
    {             
        var sections = avm.CourseSectionList;
        return Json(sections, JsonRequestBehavior.AllowGet);
    }
于 2013-08-22T08:35:04.967 回答