c# - 尝试为 StudentId=1 获取 "Grade"时出错

标签 c# entity-framework linq entity-framework-core

我有以下实体和数据库上下文类,

public class Grade
{
    public int Id { get; set; }
    public string GradeName { get; set; }

    public virtual ICollection<Student> Students { get; set; } = new HashSet<Student>();
}

public class Student
{
    public int Id { get; set; }
    public string StudentName { get; set; }
}



public class SchoolContext : DbContext
{
    public DbSet<Grade> Grades { get; set; }
    public DbSet<Student> Students { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=SchoolDB;Trusted_Connection=True;");
    }
}

执行下面的代码时出现下面的错误,这里需要做什么。谢谢!

我正在寻找不在 Student 类中添加 Grade 属性的解决方案

System.InvalidOperationException: 'The Include property lambda expression 'x => {from Student c in x.Students where ([c].Id == __studentId_0) select [c]}' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.'

static void Main(string[] args)
    {
        var studentId = 1;

        var context = new SchoolContext();
        var data = context.Grades.Include(x => x.Students.Where(c => c.Id == studentId)).SingleOrDefault();
    }

enter image description here

最佳答案

I'm looking for solution without adding Grade property in Student class

因此,您希望能够获得StudentGrade,但不想将Grade 导航属性添加到Student 让 EF Core 自然地为您处理?换句话说,失去 ORM 最大的好处之一并开始为 ORM 可以使用简单的属性访问器处理的简单请求寻找类似 SQL 的解决方案?

有很多方法可以做你想做的事,但我建议你先问问自己是否真的需要。

无论如何,一种可能的解决方案是使用带有 Any 的集合导航属性作为过滤器:

var studentGrade = context.Grades
    .FirstOrDefault(grade => grade.Students.Any(student => student.Id == studentId));

另一种是使用 LINQ 等同于 SQL 查询:

var studentGrade = (
    from grade in context.Grades
    from student in grade.Students
    where student.Id == studentId
    select grade).FirstOrDefault();

关于c# - 尝试为 StudentId=1 获取 "Grade"时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54956763/

相关文章:

c# - 将字符串从 MSSQL 转换为 MySQL

c# - 如何使用 ASP.NET MVC 中的 Entity Framework 将记录插入到具有外键的表中

c# - 在使用 Entity Fluent API 映射的 View 中使用 ROW_NUMBER 设置主键会使 linq 超时

c# - 如何在 Visual Studio 中调试单线程?

c# - 什么启动 Windows 服务安装程序的安装?

Linq Order by 当列名是动态的并作为字符串传递给函数时

c# - Linq - 项目列表 <A> 到分组列表 <B> 与列表 <B> 中的 C 对象

linq - 如何在 View 中使用 IGrouping 处理 IEnumerable?

c# - 如何从 IQueryable<T> 获取原始集合

c# - 如何在单元测试期间跳过 Fluent 验证静态函数?