Loading Entity Framework Navigation Properties with Stored Procedures

I don’t see a lot of posts about this but it is possible to achieve.


public class MyContext: DbContext
    public MyContext()
        Configuration.LazyLoadingEnabled = true;
        Configuration.ProxyCreationEnabled = true;

    public DbSet<Table1> T1 { get; set; }

    public DbSet<Table2> T2 { get; set; }

public class Table1
    public int Id { get; set; }

    public int Tabel2Id { get; set; }

    [ForeignKey("Tabel2Id ")]
    public virtual Table2 Table2 { get; set; }

public class Table2
    public int Id { get; set; }

    public string SomeValue { get; set; }

Example Stored Procedure

SELECT * FROM Table1 WHERE Id = @SearchId

Using a DbSet … this DOES NOT WORK if you are using a full DbContext class.

var searchIdParam = new SqlParameter("@SearchId", searchId);
var searchResults = _dbSet.SqlQuery("LoadMyTable1s @SearchId);

You’ll find that your navigation properties are in fact loaded. I’ve been using this since at least EF5 …

1 Comment

  1. Illia Ratkevych · December 21, 2014 Reply

    Well, it is working only because of lazy loading I suppose. Your solution not quite helpful if I want to grab an object with navigation properties by one request – before lazy load will act.

Leave a Reply

Your email address will not be published.


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