简体   繁体   中英

LINQ to SQL returns wrong results

I've been trying to solve this for the entire day.. :-(

I'm Using C# with MSSQL and querying via LINQ

I have a collection stored in studWithTuiDisc variable, It contains the following data (shown in the link below)

图片
(source: secompeusc.com )

When using this variable as reference for other LINQ Statements the results are very off, prior to this post I performed experiments to check if it really wasn't my fault that incorrect results were returned:

(1) I tried to iterate through studWithTuiDisc and then checking the relationship only in the select clause since I'm sure that this will return the desired output (see below)
Code:

var xxx = (from a in studWithTuiDisc  
           select new 
           { 
             please = a.StudentId, 
             help = _conn.EEnrolledSubjects
                    .Where(m => m.StudentId == a.StudentId)
                    .Select(m => m.StudentId)
                    .FirstOrDefault() 
           }).Distinct();

Output:
控制实验输出
(source: secompeusc.com )

As we can see the studWithTuiDisc values are the only values contained in xxx

(2) Now I tried the approach that gave me a lot of headaches (see below)
Code:

var zzz = (from a in studWithTuiDisc
           join b in _conn.EEnrolledSubjects on a.StudentId equals b.StudentId
           select new { please = a.StudentId, help = b.StudentId }).Distinct();

or

var zzz = (from a in studWithTuiDisc
           from b in _conn.EEnrolledSubjects
           where a.StudentId == b.StudentId
           select new { please = a.StudentId, help = b.StudentId }).Distinct();

Output:
实验输出
(source: secompeusc.com )

Given that we already know the values in studWithTuiDisc and since we used it as filter for _conn.EEnrolledSubjects we should be expecting results that are in studWithTuiDisc but looking at the screen shots, LINQ is not returning the proper results.

What am I doing wrong?
Has anyone experienced something like this before?
Does anyone know why this is happening?

Check what is generated/sent to SQL Server by using DataContext.Log , or SQL Profiler. I think that your queries will be different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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