I was recently looking at some changes I’d made to a project I’m working on using the Entity Framework for data access. I realised that as I had moved to using a stored procedure for the data retrieval I had lost the immediate loading of some of he object related by foreign keys. If you want to load the related entities, don’t do this:

var searchResults = _context.Database.SqlQuery<MyObject>("GetMyObjects" @UserId", inputTerm);

Do this! 🙂

var searchResults = _dbSet.SqlQuery("GetMyObjects" @UserId", inputTerm);

Executing the stored procedure on the DbSet rather than the DbContext object will load the foreign key related entities.

Tip: If your entities still aren’t loading, check to make sure you have marked them as virtual in the entity class:

public virtual Organisation Organisation { get; set; }

Using HttpClient to Send Dates in URL Using AttributeRouting
Build Process - TeamCity, NUnit, dotCover & Octopus Deploy

Discussion

Leave a Comment

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.