Could anyone explain to my why this is not working?
In the database we have Employees with an IdEmployee column. We also have some tables with foreign keys to that one.
Say we have something like this:
var employee = dataContext.Employees.First(<some predicate>); var someEntity = dataContext.SomeEntities.First(<some predicate>);
Why does this not work:
var something = someEntity.SomeThings.First(t => t.Employee == employee);
while this does:
var something = someEntity.SomeThings.First(t => t.IdEmployee == employee.IdEmployee);
I don’t get it… Isn’t the first version supposed to work? The Employee entity is from the same datacontext…
It is a little bit tricky to know for sure when you have used names like
SomeThingsandsomeEntity, but what I believe is happening is that when you’re looking atsomeEntity.SomeThings,SomeThingsis a collection ofEmployeeentities. Thus, thetin your lambda expression will refer to anEmployeeobject, giving you the ability to compare their properties.Try the following
and see if that works better.
EDIT: Actually, the
.Equals()syntax is better than the==I first proposed…EDIT2: As Sessiz Saas proposes, it is probably because of lazy loading. An alternate way of loading the employee objects is provided below:
However, remember that this could cause extra (and unnecessary, as you are able to do the job anyway) data calls.