views:

52

answers:

1

I want to declare a variable to hold the query result from LINQ to SQL like to the following:

    Dim query As IQueryable(Of Student)

    If isNoUserName Then

        query = From st In db.Students _
                Order By st.AssignedId Ascending _
                Where (st.studentId = studentId _
                Select st

    Else

        '' error here
        query = From st In db.Students _
                Order By st.firstName Ascending _
                Join user In db.MSUsers On user.UserId Equals st.UserId _
                Where st.studentId = studentId _
                Select st.firstName, st.lastName, user.userName

    End If

Return query

Error : conversions from 'System.Linq.IQueryable(Of )' to 'System.Linq.IQueryable(Of Student)'.

How do I declare variable "query" to hold both data from "Student" and "User" tables?

Thank you.

+1  A: 

query is declared as being IQueryable<Student>, but it you look at the second query, you aren't actually returning students - you are returning a compiler-generated type composed of firstName, lastName and userName. Try changing the second query to end with:

Select st;

Edit:

Re needing data other than st, then you might try a trick to give query a type; I'll use C# for my illustration, as my VB is read-only:

var query = Enumerable.Repeat(new {firstName="",lastName="",userName=""}, 0);
...
if(isNoUserName) {
    query = ...
            select new {st.firstName, st.lastName, userName = ""};
} else {
    query = ...
            select new {st.firstName, st.lastName, user.userName };
}
Marc Gravell
I need both data from student and user tables. How can I declare the query variable?
Narazana
@Narazana - I'll edit to illustrate
Marc Gravell
You should create a new class called my QueryResults that has all the common fields you require and `Select new QueryResults { fn = st.firstName, ln = st.lastName, un = user.userName }` (the syntax might be a little off there, I'm C#) - do that for both queries.
uosɐſ
(You could do that without defining QueryResult, but that's too complicated for today's lesson...)
uosɐſ
@uosɐſ show me without defining ʇןnsǝɹʎɹǝnb as long as I learn something it's ok if it's pǝʇɐɔıןdɯoɔ . Example in C# is fine with me too.
Narazana
Well, Marc showed you in his edited example. But that has limited use - you can use such results locally, but you can't pass them around or return to a caller. If you're just doing some local calculation, then the "anonymous type" (as it's called, a type without a name) will work.
uosɐſ