• behance
  • gitHub
  • google
  • linkedin
  • twitter
Entity Framework Code-First Stored Procedures & Foreign Key Entities

Entity Framework Code-First Stored Procedures & Foreign Key Entities

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; }

1 Comment

  1. avatar
    Anton · May 26, 2015 Reply

    Fantastic! you save my time!

Leave a reply

*