1

I have 2 Generic Lists called Students and Entries They are in 1 to 0..1 relationship. Students 1:0..1 Entries

I want to get the list of Student Name, ID and English, Maths detail from Entries if exists.

My LINQ query is as below and I got the null reference error at se.English. Could you pls help? Thanks.

var query = from s in students
            join t in entries
            on s.StudentDetailID equals t.StudentDetailID into StudentEntries
            from se in StudentEntries.DefaultIfEmpty()                                    
            select new { s.StudentDetailID, s.LastName, s.FirstName,
            se.English};

2 Answers 2

1

As you said you have a 1-0..1 relationship so it is possible that se.english will be null(because you used an left outer join), you should handle it in your query, I assumed it it would be String and put "" if it is null, You can handle it as you wish.

var query = from s in students
            join t in entries
            on s.StudentDetailID equals t.StudentDetailID into StudentEntries
            from se in StudentEntries.DefaultIfEmpty()                                    
            select new { s.StudentDetailID, s.LastName, s.FirstName,
            English = se.English?? ""};
Sign up to request clarification or add additional context in comments.

Comments

0

se could be null, because you assigned it StudentEntries.DefaultIfEmpty(). And Default of a class is null. So you can't call se.English without testing it for null before:

var query = from s in students
        join t in entries
        on s.StudentDetailID equals t.StudentDetailID into StudentEntries
        from se in StudentEntries.DefaultIfEmpty()                                    
        select new { s.StudentDetailID, s.LastName, s.FirstName,
        se == null ? null : se.English};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.