1

I have an sql statement that I'd like to return a list of Persons that have a related Department entity. The Person class has a Department ID and with the magic of entity framework it associates the correct Department object when I load it from the database.

My SQL statement is:

SELECT *
FROM PERSON
    INNER JOIN DEPARTMENT ON PERSON.DEPARTMENT_ID = DEPARTMENT.ID
WHERE UPPER(FORENAME) LIKE '%RALPH%'
ORDER BY SURNAME

In MSSMS when I run the query I get the following results:

enter image description here

However, when I run the sql using DbSet.SqlQuery() I get the following results:

enter image description here

Note how the department object is null in the first item, yet has been populated in the second item.

I know I haven't provided much information, I'm hoping there's just a simple answer for this.

By the way..

DataContext.Configuration.LazyLoadingEnabled = false;

LazyLoadingEnabled is set to false as you can see, I know changing this to true would fix the issue. I'd just rather not go enabling it for whichever call I fancy needs it.

Thanks guys

6
  • 1
    Why are you using SqlQuery and not a proper EF query? Commented Sep 26, 2017 at 12:39
  • I have a list of People that I perform a filter on.. using the criteria provided by the user I generate an sql statement. There are many potential variations of the search so an sql statement seemed like the way to go. Commented Sep 26, 2017 at 12:43
  • It's almost certainly not the way to go, otherwise there's no point in using EF. Commented Sep 26, 2017 at 12:44
  • Okay, well I appreciate your comment and I shall see about changing that! Do you care to provide a reason of why the following is happening anyway? Commented Sep 26, 2017 at 12:46
  • Had you previously loaded the Department into that DbContext instance? If so EF will recognize that it already has the Department with DepartmentId=2, and will set the navigation property to that instance. Commented Sep 26, 2017 at 12:59

1 Answer 1

1

If you have previously loaded the Department into that DbContext instance, EF Change Tracking will recognize that it already has the Department with DepartmentId=2, and will set the navigation property to that instance.

Sign up to request clarification or add additional context in comments.

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.