gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:36:18 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com