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

  • Home
  • SEARCH
  • 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 8856393
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T14:20:49+00:00 2026-06-14T14:20:49+00:00

I’m new to Entity Framework and am trying to learn how to use Code

  • 0

I’m new to Entity Framework and am trying to learn how to use Code First to load entities from the database.

My model contains a user:

public class User
{
    public int UserID { get; set; }

    [Required]
    public string Name { get; set; }

    // Navigation Properties
    public virtual ICollection<AuditEntry> AuditEntries { get; set; }
}

Each user can have a set of audit entries each of which contains a simple message:

public class AuditEntry
{
    public int AuditEntryID { get; set; }

    [Required]
    public string Message { get; set; }

    // Navigation Properties
    public int UserID { get; set; }
    public virtual User User { get; set; }
}

I have a DBContext which just exposes the two tables:

public DbSet<User> Users { get; set; }
public DbSet<AuditEntry> AuditEntries { get; set; }

What I want to do is load a list of AuditEntry objects containing the message and the related User object containing the UserID and Name properties.

List<AuditEntry> auditEntries = db.AuditEntries.ToList();

Because I have my navigation properties marked as virtual and I haven’t disabled lazy loading, I get an infinitely deep object graph (each AuditEntry has a User object, which contains a list of the AuditEntries, each of which contains a User object, which contains a list of AuditEntries etc)

This is no good if I then want to serialize the object (for example to send as the result in a Web API).

I’ve tried turning off lazy loading (either by removing the virtual keywords from my navigation properties in the model, or by adding this.Configuration.LazyLoadingEnabled = false; to my DBContext). As expected this results in a flat list of AuditEntry objects with User set to null.

With lazy loading off, I’ve tried to eager load the User like so:

var auditentries = db.AuditEntries.Include(a => a.User);

but this results in the same deep / cyclic result as before.

How can I load one level deep (e.g. include the user’s ID and name) without also loading back-references / following navigation properties back to the original object and creating a cycle?

  • 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-06-14T14:20:50+00:00Added an answer on June 14, 2026 at 2:20 pm

    After much hacking, I’ve come up with the following potential solution using a dynamic return type and projection in my Linq query:

    public dynamic GetAuditEntries()
    {
        var result = from a in db.AuditEntries
                     select new
                     {
                         a.AuditEntryID,
                         a.Message,
                         User = new
                         {
                             a.User.UserID,
                             a.User.Username
                         }
                     };
    
        return result;
    }
    

    This produces (internally) the following SQL which seems sensible:

    SELECT 
    [Extent1].[AuditEntryID] AS [AuditEntryID], 
    [Extent1].[Message] AS [Message], 
    [Extent1].[UserID] AS [UserID], 
    [Extent2].[Username] AS [Username]
    FROM  [dbo].[AuditEntries] AS [Extent1]
    INNER JOIN [dbo].[Users] AS [Extent2] ON [Extent1].[UserID] = [Extent2].[UserID]
    

    This produces the results that I’m after, but it seems a bit long winded (especially for real life models that would be significantly more complex than my example), and I question the impact this will have on performance.

    Advantages

    • This gives me a lot of flexibility over the exact contents of my returned object. Since I generally do most of my UI interaction / templating on the client side, I frequently find myself having to create multiple versions of my model objects. I generally need a certain granularity over which users can see which properties (e.g. I might not want to send every user’s email address to low-privilege user’s browser in an AJAX request)

    • It allows entity framework to intelligently build the query and only select the fields that I have chosen to project. For example, inside each top level AuditEntry object, I want to see User.UserID and User.Username but not User.AuditEntries.

    Disadvantages

    • The returned type from my Web API is no longer strongly typed so I couldn’t create a strongly typed MVC view based on this API. As it happens this is not a problem for my particular case.

    • Projecting manually in this way from a large / complex model could result in a lot of code, seems like a lot of work and has the potential to introduce errors in the API. This would have to be carefully tested.

    • The API method becomes tightly coupled with the structure of the model and since this is no longer fully automated based on my POCO classes, any changes made to the model would have to be reflected in the code that loads them.

    Include method?

    I’m still a little confused about the use of the .Include() method. I understand that this method will specify that related entities should be “eager loaded” along with the specified entity. However, since the guidance seems to be that navigation properties should be placed on both sides of a relationship and marked as virtual, the Include method seems to result in a cycle being created which has a significant negative impact on it’s usefulness (especially when serializing).

    In my case the “tree” would look a little like:

    AuditEntry
        User
            AuditEntries * n
                User * n
                    etc
    

    I’d be very interested to hear any comments about this approach, the impact of using dynamic in this way or any other insights.

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

Sidebar

Related Questions

I want use html5's new tag to play a wav file (currently only supported
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I have a view passing on information from a database: def serve_article(request, id): served_article
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i

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.