【问题标题】:Add properties to entity framework query including the object itself向实体框架查询添加属性,包括对象本身
【发布时间】:2013-07-07 20:53:54
【问题描述】:

考虑这个将在 MVC 控制器中使用的查询:

return
    from student in Students
    where //..
    select student;

结果将被转换为 JSON,如:

[
    {firstName: "John", lastName="Smith"},
    ...
]

我想要查询以包含这样的课程计数:

[
    {firstName: "John", lastName="Smith", courseCount: "4"},
    ...
]

第一个解决方案是使用匿名对象创建查询,如下所示:

return
    from student in Students
    join course in Customers on course.StudentId equals student.Id 
    where //..
    group by //...
    select new {student.FirstName, student.LastName, CourseCount = courseGroup.Count()};

但是这样我就失去了学生的整个对象。例如,如果我稍后将Age 属性添加到学生,我应该更新此查询并将student.Age 添加到选择部分。但是在第一个解决方案中,结果会自动包含该字段。

我正在寻找一种更强大的解决方案来执行此选择,因此对 Student 类的所有更改都会自动传播到结果中。

解决方法: 这将是一个解决方案,但它会更改 JSON 格式并且听起来有点棘手。我正在寻找更好的解决方案。 (也许是动态对象!)

select new { Student = student, CourseCount = courseGroup.Count()};

编辑: 所需的解决方案是这样的:

select new Student(student){CourseCount = courseGroup.Count()}

以动态方式添加 CourseCount!

【问题讨论】:

  • 您的最后一个 sn-p 不是 dynamic,但它看起来像解决方案。
  • @HenkHolterman:但它改变了生成的 JSON。我希望 JSON 像以前一样保持平坦。类似select new Student(student){CourseCount = courseGroup.Count()}。以动态方式添加CourseCount

标签: c# linq entity-framework linq-to-entities


【解决方案1】:

您可以对课程进行左连接,从而获得您想要的结果。

[代码] 返回 来自学生中的学生 加入客户课程中 course.StudentId 等于 student.Id

进入课程组 来自 courseGroup.DefaultIfEmpty() 中的课程

where //..
select new {student.FirstName, student.LastName, CourseCount = courseGroup.Count()};

[代码]

如果您执行 GroupBy,它将取消学生课程,然后您必须执行类似... courseGroup.StudentFirstName ... 的操作,具体取决于您的 GroupBy 的样子。

【讨论】:

  • 问题不在于如何分组,问题在于我不想明确使用student.FristName, student.LastName 来使查询对更改更加健壮。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-27
  • 1970-01-01
  • 2011-04-27
  • 2017-03-02
  • 1970-01-01
  • 2012-06-05
相关资源
最近更新 更多