2

I use VS 2008 and ado.net EF. I have two tables:

Shifts(SH_Id, WorkshopId,TabNum)
Workshops(WH_ID, WH_Name)

Shifts linked to Workshops(WorkshopId -- WH_ID) I'm trying to write query:

var data = _Context.Shifts.Where(w => w.TabNum == 1).First();
var workshop = data.Workshops.WH_ID;

It returns NullReferenceException. But following code returns WH_ID:

        var data2 = (from o in _Context.Shifts
                    where o.TabNum == 1
                    select new
                    {
                        wh_id = o.Workshops.WH_Id

                    });

        var workshop = data2.First().Workshops.wh_id;

Why data.Workshops.WH_ID returns NullReferenceException?

user2273044
  • 161
  • 2
  • 17
  • because data2 may have no items, so asking for the First() method will throw `NullReferenceException` – Mahdi Tahsildari Mar 17 '14 at 13:57
  • Your second approach returns some value as WH_Id or it just does not throws exception, and value is null? – Sergey Berezovskiy Mar 17 '14 at 13:57
  • If to use SQL Server query SELECT WorkshopId FROM SHIFTS WHERE TabNum = 1, wll be returned one record. Second aproach returns required value – user2273044 Mar 17 '14 at 13:59
  • Possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Nasreddine Oct 04 '15 at 09:10

2 Answers2

2

This is happening because the Entity framework is not returning the attached entities from the query.

The reason why this works for the second example is because the entire query is translated to SQL and run on the server.

To solve this try

var data = _Context.Shifts.Include("Workshops").Where(w => w.TabNum == 1).First();

or even

var data = _Context.Shifts.Include("Workshops").First(w => w.TabNum == 1);
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
-2

You are not sure if there are any items in the sequence, so check it firs:

var data2 = (from o in _Context.Shifts
             where o.TabNum == 1
             select new
             {
                wh_id = o.Workshops.WH_Id

             });

if(data2.Count() > 0)
{
    var workshop = data2.First().wh_id;
    ...
}
Mahdi Tahsildari
  • 13,065
  • 14
  • 55
  • 94