Menu

Entity Framework Code-First Stored Procedures & Foreign Key Entities

August 16, 2013 - .NET / C#, Entity Framework, Geek Bits
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; }
Share

One thought on “Entity Framework Code-First Stored Procedures & Foreign Key Entities

avatar
Anton

Fantastic! you save my time!

Reply

Leave a Reply

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

*