简体   繁体   English

向实体框架查询添加属性,包括对象本身

[英]Add properties to entity framework query including the object itself

Consider this query which is going to be used in a MVC controller: 考虑将在MVC控制器中使用的以下查询:

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

the result will be converted to JSON like: 结果将转换为JSON,例如:

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

I want to have a query to include courses count like this: 我想查询包含课程数的查询,如下所示:

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

first solution is to create a query using anonymous objects like this: 第一种解决方案是使用如下匿名对象创建查询:

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()};

But in this way I lost the whole object of student. 但是这样我就失去了学生的全部目标。 For example if I add Age property to student later, I should update this query and add student.Age to the select part. 例如,如果稍后向学生添加Age属性,则应更新此查询,然后将student.Age添加到select部分。 But in the first solution, the result includes this field automatically. 但是在第一个解决方案中,结果自动包含此字段。

I'm looking for a more robust solution to do this select, so all changes to the Student class propagate to the result automatically. 我正在寻找一种更强大的解决方案来执行此选择,因此对Student类的所有更改都会自动传播到结果。

Workaround: This would be a solution, but it changes the JSON format and sounds a little tricky. 解决方法:这将是一个解决方案,但是它更改了JSON格式并且听起来有些棘手。 I'm looking for a better solution. 我正在寻找更好的解决方案。 (Maybe with dynamic objects!) (也许带有动态对象!)

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

EDIT: The desired solution is would be something like this: 编辑:所需的解决方案是这样的:

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

Adding CourseCount in a dynamic way! 以动态方式添加CourseCount!

You could do a left join on the courses which would give you the results that you want. 您可以对课程进行左联接,这将为您提供所需的结果。

[code] return from student in Students join course in Customers on course.StudentId equals student.Id [代码]学生返回的学生在课程中加入客户的课程。StudentId等于student.Id

into courseGroup from course in courseGroup.DefaultIfEmpty() 从courseGroup.DefaultIfEmpty()中的课程进入courseGroup

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

[code] [码]

If you do a GroupBy it will cancel out the student class and you would then have to do something like... courseGroup.StudentFirstName ... Depending on what your GroupBy looks like. 如果您使用GroupBy,它将取消学生班级,然后您必须执行类似... courseGroup.StudentFirstName ...的操作,具体取决于您的GroupBy外观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM