Narazana
Narazana

Reputation: 1950

Cannot assign LINQ query to variable

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.

Upvotes: 1

Views: 1911

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062600

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

Upvotes: 1

Related Questions