Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why LINQ 2 SQL sometime add a field like select 1 as test, others valid fields

Tags:

linq-to-sql

I have to concat 2 linq2sql query and I have an issue since the 2 query doesn't return the same number of columns, what is weird is after a .ToList() on the queries, they can concat without problem.

The reason is, for some linq2sql reason, I have 2 more column named test and test2 which come from 2 left outer join that linq2sql automatically create, something like "select 1 as test, tablefields"

Is there any good reason for that? how to remove this extra "1 as test" field?

here a few of examples of what it look like: google result for linq 2 sql "select 1 as test"

like image 890
Fredou Avatar asked Apr 21 '10 18:04

Fredou


1 Answers

OK, let's assuming we have 2 tables: dbo.User and dbo.Client. Each client may be connected (or not) to user. So client records have a nullable foreign key field identifying a user.

For the query:

var query = context.Clients
      .Select(c => c.User);

LINQ will produce something similar to:

SELECT [t2].[test], [t2].[Id], [t2].[Username], ...
FROM [dbo].[Client] AS [t0]
LEFT OUTER JOIN (
    SELECT 1 AS [test], [t1].[Id], [t1].[Username], ...
    FROM [dbo].[User] AS [t1]
    ) AS [t2] ON [t2].[Id] = [t0].[UserId]

Since not all client records have a matching user record, LINQ is creating a query that ensures there will be a row filled with nulls for every userless client. This is done by creating an extra dummy column called [test].

So rows which have [test] column value set to 1 are really connected to user entity.

I suppose this [test] column is used by LINQ as a flag that means "hey, here is a client with user defined".

If I decide to rewrite this query, I'll use user primary key as the indicator, but it seems for LINQ it is easier to use [test] column.

like image 145
Oleks Avatar answered Oct 19 '22 15:10

Oleks