Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6111937
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T14:41:16+00:00 2026-05-23T14:41:16+00:00

I have two simple POCO classes; I’m trying to get the MyY property below

  • 0

I have two simple POCO classes; I’m trying to get the MyY property below hydrated with the an instance of Y. I’ve tried a number of ways to do this, and think I might be missing something obvious or simple.

public class X
{
     public int Id { get; set;}
     public virtual Y MyY { get; set; }
}

public class Y
{
     public int Id { get; set; }
     // ...
}

I’ve turned lazy loading off via this call in my subclass of DbContext‘s constructor:

Configuration.LazyLoadingEnabled = false;

When retrieving an X I have tried

context.Set<X>.Include("MyY").FirstOrDefault(x => ....);

which did not work. I tried

var result = context.Set<X>.FirstOrDefault(x => ....);
context.Entry(result).Reference("MyY").Load();

which works, but requires two round-trips to the database. I tried

context.Set<X>.Select(x => new { X = x, Y = x.MyY }).FirstOrDefault(x => ...);

which also works, but “weakens” my model (ordinarily projecting to a new type is not so bad, but the “shape” of these EF POCOs works perfectly for the DTOs I’ll be sending through WCF later).

I finally tried removing virtual from the MyY property as suggested in an answer to another question, but that had no effect at all.

Finally, I want to use the generic repository pattern. What I have ended up with is the following design, shown in part, which supports explicit-load (not preferred) and eager-load when modified to work properly. How do I modify it to get the single db round-trip eager-load?

public class EFRepository : IRepository
{
    public T Get<T>(Specification<T> specification) where T : class, IEntity
    {
        var result = ApplyEagerLoading(context.Set<T>()).FirstOrDefault(specification.IsMatch);
        ApplyPostQueryLoading(new List<T> { result });
        return result;
    }

    // doesn't really seem to work yet...
    private DbSet<T> ApplyEagerLoading<T>(DbSet<T> set) where T : class, IEntity
    {
        var ls = loadSpecs.GetOrAdd(typeof(T), () => new List<LoadSpec>());
        foreach (var spec in ls.Where(s => !s.ExplicitLoad))
            set.Include(spec.PropertyName);
        return set;
    }

    // works, but wrong on so many levels...
    private void ApplyPostQueryLoading<T>(IEnumerable<T> entities) where T : class, IEntity
    {
        var ls = loadSpecs.GetOrAdd(typeof(T), () => new List<LoadSpec>());
        foreach (var e in entities)
            foreach (var spec in ls.Where(s => s.ExplicitLoad))
                if (spec.IsCollection)
                    context.Entry(e).Collection(spec.PropertyName).Load();
                else
                    context.Entry(e).Reference(spec.PropertyName).Load();
    }

    private readonly IDictionary<Type, IList<LoadSpec>> loadSpecs = new Dictionary<Type, IList<LoadSpec>>();

    private class LoadSpec
    {
        internal string PropertyName;
        internal bool ExplicitLoad;
        internal bool IsCollection;
    }
}

Example uses:

// add a rule to load MyY explicitly
repository.AddLoadRule<X>(x => x.MyY, explicit:true, isCollection:false)
...
var x = repository.Get<X>(new Specification<X>(x => x.Id == 5));

// add a rule to load MyY with X
repository.AddLoadRule<X>(x => x.MyY, explicit:false)
...
// x.MyY will be null! Doesn't work!
var x = repository.Get<X>(new Specification<X>(x => x.Id == 5));

An Update Based on The Answer:

It turns out my temp code examples lied (those one-liners above). I had actually cached the result of .Include in a local variable but applied the .FirstOrDefault against the .Set<X> not the result of .Include. Here is the fix to ApplyEagerLoading, which mirrors what others have suggested in related questions:

    private IQueryable<T> ApplyEagerLoading<T>(IEnumerable<T> set) where T : class, IEntity
    {
        var ls = loadSpecs.GetOrAdd(typeof(T), () => new List<LoadSpec>());
        var query = set.AsQueryable();
        return ls.Where(s => !s.ExplicitLoad).Aggregate(query, (current, spec) => current.Include(spec.PropertyName));
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T14:41:17+00:00Added an answer on May 23, 2026 at 2:41 pm

    This should work:

    X entity = context.Set<X>().Include(x => x.MyY).FirstOrDefault();
    

    IF it doesn’t the problem must be elsewhere.

    If you need some eager loading strategy check this answer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a simple question (working with Java). I have two classes, one represents
I have two simple tables in my database. A card table that contains Id,
I have two simple while loops in my program that I feel ought to
Simple idea: I have two images that I want to merge, one is 500x500
I have two webapplication, one is a simple authenticationsite which can authenticate the logged
Simple ASP.NET application. I have two drop-down controls. On the first-drop down I have
Ok, i have simple scenario: have two pages: login and welcome pages. im using
I have a simple database with two tables. Users and Configurations. A user has
I have a really simple class with two methods; One that will be called
I have a simple scenario, where two servers are connected through a gigabit link.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.