7 Replies - 13049 Views - Last Post: 25 July 2012 - 01:36 PM

#1 ItIntern3  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 97
  • Joined: 14-July 10

Returning Data from LINQ Query Method

Posted 25 July 2012 - 05:45 AM

Hi all,

I am trying to return a linq query from a method and am having some trouble determining the return type to this method. I have consulted a few sources and have not had any luck finding a method returns a query joining together multiple tables. The method is as follows:

public static List<Session> SessionQueries()
        {
            using(var db = new LearningServicesEntities())
            {
               var query = (from session in db.Sessions
                                      join tuteeStudent in db.Students on session.TuteeStudentID equals tuteeStudent.StudentID
                                      join tutorStudent in db.Students on session.TutorStudentID equals tutorStudent.StudentID
                                      join c in db.Courses on session.CourseID equals c.CourseID
                                 select new {session.Date, session.Time, tuteeStudent.FullName, c.CourseNumber, c.CourseName, session.In, session.Out, session.Office}).ToList();
                return query.ToList();
            }
        }



The query variable in this method does not simply return a list a sessions, however, it returns a list of anonymous types and I do not know how to handle this. I eventually will call this method in the controller to pass the returned data to a view. Any help on this topic would be very much appreciated. Thank you in advance.

Is This A Good Question/Topic? 0
  • +

Replies To: Returning Data from LINQ Query Method

#2 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2216
  • View blog
  • Posts: 9,351
  • Joined: 29-May 08

Re: Returning Data from LINQ Query Method

Posted 25 July 2012 - 05:59 AM

This part of the LINQ query
select new {session.Date, session.Time, tuteeStudent.FullName, c.CourseNumber, c.CourseName, session.In, session.Out, session.Office}

is called a projection, or transform.

You are projecting the data into an anonymous type.

If you want it to return your type session then create instances of that type.
Was This Post Helpful? 1
  • +
  • -

#3 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,957
  • Joined: 21-March 08

Re: Returning Data from LINQ Query Method

Posted 25 July 2012 - 06:06 AM

As Adam states, you are creating an anonymous type.

Change this...

select new {session.Date, session.Time, tuteeStudent.FullName, c.CourseNumber, c.CourseName, session.In, session.Out, session.Office}).ToList();



to

select new Session { Date = session.Date, Time = session.Time, FullName = tuteeStudent.FullName, CourseNumber = c.CourseNumber, CourseName = c.CourseName, In = session.In, Out = session.Out, Office = session.Office}).ToList();



I completely guessed at the properties in Session as you didn't give the class definition.

Basically, the select new Session will create a new Session object for each record in the query. Inside the braces, you will assign values from the query to the properties of the Session object.
Was This Post Helpful? 1
  • +
  • -

#4 ItIntern3  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 97
  • Joined: 14-July 10

Re: Returning Data from LINQ Query Method

Posted 25 July 2012 - 06:23 AM

Thank you for your quick responses!

(I am getting an error on the columns I would like to display from the other tables because they are not session properties). There isn't a way I can return the anonymous type from the method? If not, then in order to return queries that join to different tables, can I create model classes (class.cs) files and place them in the MVC project models folder and query from there? Right now I am working with an Entity Data Model.
Was This Post Helpful? 0
  • +
  • -

#5 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,957
  • Joined: 21-March 08

Re: Returning Data from LINQ Query Method

Posted 25 July 2012 - 08:00 AM

You can create another class which would simply be a class that represents the data that is returned from this query.

Like so..

public class SessionQueryResult
{
    public DateTime Date { get; set; }
    public DateTime Time { get; set; }
    public string FullName { get; set; }
    public string CourseNumber { get; set; }
    // and the rest of the properties
}



then your select statement would create a new SessionQueryResult object, and you would assign the values from the query to the properties. That will make the properties line up with what you are wanting from the query.

Just remember, if you do this for every query, then you are going to have a lot of "result" classes. If you can get the data that you want into an object that already exists, then that would be better. If not, you can still do this.
Was This Post Helpful? 1
  • +
  • -

#6 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2216
  • View blog
  • Posts: 9,351
  • Joined: 29-May 08

Re: Returning Data from LINQ Query Method

Posted 25 July 2012 - 08:10 AM

You could make it return a generic type
public static List<T> SessionQueries<T>()
        {
            using(var db = new LearningServicesEntities())
            {
               var query = (from session in db.Sessions
                                      join tuteeStudent in db.Students on session.TuteeStudentID equals tuteeStudent.StudentID
                                      join tutorStudent in db.Students on session.TutorStudentID equals tutorStudent.StudentID
                                      join c in db.Courses on session.CourseID equals c.CourseID
                                 select new {session.Date, session.Time, tuteeStudent.FullName, c.CourseNumber, c.CourseName, session.In, session.Out, session.Office}).ToList();
                return query.ToList();
            }
        }



but that also means that all other methods that utilise the results also have to generic input parameters.

It be simple to create a new type class that encapsulates conceptually what you are returning.

This post has been edited by AdamSpeight2008: 25 July 2012 - 08:12 AM

Was This Post Helpful? 1
  • +
  • -

#7 ItIntern3  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 97
  • Joined: 14-July 10

Re: Returning Data from LINQ Query Method

Posted 25 July 2012 - 08:39 AM

View Posteclipsed4utoo, on 25 July 2012 - 10:00 AM, said:

You can create another class which would simply be a class that represents the data that is returned from this query.

Like so..

public class SessionQueryResult
{
    public DateTime Date { get; set; }
    public DateTime Time { get; set; }
    public string FullName { get; set; }
    public string CourseNumber { get; set; }
    // and the rest of the properties
}



then your select statement would create a new SessionQueryResult object, and you would assign the values from the query to the properties. That will make the properties line up with what you are wanting from the query.

Just remember, if you do this for every query, then you are going to have a lot of "result" classes. If you can get the data that you want into an object that already exists, then that would be better. If not, you can still do this.


I was also thinking the same thing, that there could potentially be a lot of different types of classes. I have seen in other projects a "result type class file" (say a resultType.cs file) used to store result types from queries. I just wasn't sure what path I wanted to take, and think that this is a more attractive option then working with generics.

I also have a question about putting together different model classes based on the different database tables represented by my entity diagram. Is there any advantage to creating model.cs files in the web app's model folder, or can I just work with the entity data model directly when reading data from and writing data to the database?

For example: if I have tables: Course, Professor, Student and Session in my model, and I create .cs files named: CourseModel.cs, ProfessorModel.cs, StudentModel.cs, and SessionModel.cs (all located in the web app's Model folder), what functionality do I pick up/lose than if I were just pulling data from the EDM directly? (ignoring complex queries that include properties from multiple models).
Was This Post Helpful? 0
  • +
  • -

#8 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2216
  • View blog
  • Posts: 9,351
  • Joined: 29-May 08

Re: Returning Data from LINQ Query Method

Posted 25 July 2012 - 01:36 PM

The problem isn't to due with Generic, but the Anonymous Type generated by the compiler.

To the coder, it a type that can not be named or written by the user. The use of return a generic type is the compiler knows what is type, so can infer what the return type should be. If you think why not use Object instead since all types inherit from it, the trouble lie in casting in to definitive type. You can't named the type, you can't cast to. Plus if you could cast to it, you could just return that type to begin with.

Generic are good think as it allows you reuse sections of code. LINQ uses generic intensely.

For example the following extension method, allows you to filter and transform a sequence.
public static IEnumerable<T_Out> FilterAndTransform<T_In,T_Out> 
 (this IEnumerable<T_In> source,
     Func<T_In, Boolean> filter,
    Func<T_In, T_Out> transform) 
{
 foreach(T_In elem in source)
 {
  if( filter( elem ) )
  {
    yield transform( elem) ;
  }
 }
}   



It works for any IEnumerable<T> saving you to having write one for each possible type.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1