我创建了一个JoinModel类来连接多个表的课程列表,即Model文件夹下的课程摘要。以前工作正常。现在,我添加了一个包含新年,课程表2019的表格,并将课程表2019添加到CourseDateModel.cs中。但是我收到错误消息,抱怨“无法在LINQ to Entities查询中构造”。我正在使用Entity Framework 6,首先使用代码生成CourseDataModel.cs文件。下面是我的代码:
CourseDataModel.cs
namespace course.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class CourseDataModel : DbContext
{
public CourseDataModel()
: base("name=CourseDataModel")
{
}
public virtual DbSet<courselist> courselist { get; set;
public virtual DbSet<courselist2019> courselist2019 { get; set; }
public virtual DbSet<contentsummary> contentsummary { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
JoinModel.cs
public class JoinModel
{
[Key]
public int id { get; set; }
public contentsummary Contentsummary { get; set; }
public courselist Courselist { get; set; }
public courselist2019 Courselist2019 { get; set; }
}
HomeController.cs
public ActionResult Index( )
{
var searchResults = (from a in db.courselist
join b in db.coursesummary on
new { subject=a.subject, catalog=a.catalog } equals
new { subject=b.Subject, catalog=b.Catalogno } into ab
where a.active ==true
from b in ab.DefaultIfEmpty()
select new JoinModel
{
Courselist = a,
Contentsummary = b
}).ToList();
return View(searchResults);
}
我尝试更改查询
var searchResults = (from a in db.courselist
join b in db.coursesummary on
new { subject=a.subject, catalog=a.catalog } equals
new { subject=b.Subject, catalog=b.Catalogno } into ab
where a.active ==true
from b in ab.DefaultIfEmpty()
//select new JoinModel
select new
{
Courselist = a,
Contentsummary = b
}).ToList()
.Select(x=>new JoinModel(){Courselist=x.a, Contentsummary=x.b});
答案 0 :(得分:0)
我发现CourseDataModel.cs文件包含系统生成的额外代码行。我注释掉了,现在可以正常工作:
//public System.Data.Entity.DbSet<course.Models.JoinModel2019> JoinModel2019 { get; set; }