【问题标题】:One to many linq Eager load一对多 linq 急切负载
【发布时间】:2017-11-10 19:32:00
【问题描述】:

我正在使用以下技术:C#、SQL Server、ASP.NET 和 Entity Framework 以及 Linq。 我有一个多对多的关系,使用急切的负载。 我想获取一个学生注册的所有课程。如您所见,我有一个从学生到题词表的一对多关系。

模型类:

public class Courses
{
    [Required]
    public int Id { get; set; }
    //more properties here
     public student stud { get; set; }
}

public class Enroll
{
    [Key]
    public intId { get; set; }
    //properties here
    [Required]
    public string StudentId{ get; set; }
    public Courses Courses{ get; set; }
}
public class student{
 public intId { get; set; }
  //other properties
  public Inscripe Inscription {get;set}
}

这是我的控制器:

public IEnumerable<course> GetCoursesStudent(Int studentId)
{
     //some code here to validate
     var result = _dbContext
.Enroll.Include(c => c.Courses)
.Where(c => c.StudentId == studentId)
.SelectMany(c => c.Courses).ToList();
}

问题: 我从 SelectMany 收到一个错误:无法从用法中推断方法 Queribly.selectMany(IQueryableExpression>> 的类型参数。

我该如何解决?

【问题讨论】:

  • 请复制粘贴错误。
  • 另外,我不认为“inscribe”是你认为的意思——你的意思似乎是“enroll”。
  • 有人可以让我知道为什么要否决我的问题?至少我可以知道如何提高我的问题质量!不要只是投反对票,就像拖钓一样。
  • Courses 不是一个集合,所以 SelectMany 不合适。使用Select。或将Courses 设为收藏。
  • 将鼠标悬停在拒绝投票按钮上可以查看拒绝投票的原因。不需要发表评论,当然不是“像拖钓一样”。

标签: c# asp.net linq


【解决方案1】:

您为 IEnumerable 指定的类型错误。它应该是“课程”而不是“课程”:

public IEnumerable<Courses> GetCoursesStudent(Int studentId)
{
    var result = _dbContext
        .Enroll
        .Include(c => c.Courses)
        .Where(c => c.StudentId == studentId)
        .SelectMany(c => c.Courses)
        .ToList();
}

Enroll 类的“Courses”属性应该是可枚举的:

public class Enroll
{
    [Key]
    public intId { get; set; }

    [Required]
    public string StudentId { get; set; }
    public IEnumerable<Courses> Courses { get; set; }
}

【讨论】:

    猜你喜欢
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 2021-12-01
    相关资源
    最近更新 更多