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 7075999
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T06:14:43+00:00 2026-05-28T06:14:43+00:00

I’m using the Entity Framework version 4.2. There are two classes in my small

  • 0

I’m using the Entity Framework version 4.2. There are two classes in my small test app:

public class TestParent
{
    public int TestParentID { get; set; }
    public string Name { get; set; }
    public string Comment { get; set; }

    public virtual ICollection<TestChild> TestChildren { get; set; }
}

public class TestChild
{
    public int TestChildID { get; set; }
    public int TestParentID { get; set; }
    public string Name { get; set; }
    public string Comment { get; set; }

    public virtual TestParent TestParent { get; set; }
}

Populating objects with data from the database works well. So I can use testParent.TestChildren.OrderBy(tc => tc.Name).First().Name etc. in my code.

Then I built a standard edit form for my testParents. The controller look like this:

public class TestController : Controller
{
    private EFDbTestParentRepository testParentRepository = new EFDbTestParentRepository();
    private EFDbTestChildRepository testChildRepository = new EFDbTestChildRepository();

    public ActionResult ListParents()
    {
        return View(testParentRepository.TestParents);
    }

    public ViewResult EditParent(int testParentID)
    {
        return View(testParentRepository.TestParents.First(tp => tp.TestParentID == testParentID));
    }

    [HttpPost]
    public ActionResult EditParent(TestParent testParent)
    {
        if (ModelState.IsValid)
        {
            testParentRepository.SaveTestParent(testParent);
            TempData["message"] = string.Format("Changes to test parents have been saved: {0} (ID = {1})",
                                                        testParent.Name,
                                                        testParent.TestParentID);
            return RedirectToAction("ListParents");
        }
        // something wrong with the data values
        return View(testParent);
    }
}

When the form is posted back to the server the model binding appears to be working well – i.e. testParent looks okay (id, name and comment set as expected). However the navigation property TestChildren remains at NULL.

This I guess is not sooo surprising since the model binding merely extracts the form values as they were sent from the browser and pushes them into an object of the TestParent class. Populating testParent.TestChildren however requires an immediate roundtrip to the database which is the responsibility of the Entity Framework. And EF probably doesn’t get involved in the binding process.

I was however expecting the lazy loading to kick in when I call testParent.TestChildren.First(). Instead that leads to an ArgumentNullException.

Is it necessary to tag an object in a special way after model binding so that the Entity Framework will do lazy loading? How can I achieve this?

Obviously I could manually retrieve the children with the second repository testChildRepository. But that (a) doesn’t feel right and (b) leads to problems with the way my repositories are set up (each using their own DBContext – which is an issue that I haven’t managed to come to terms with yet).

  • 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-28T06:14:44+00:00Added an answer on May 28, 2026 at 6:14 am

    In order to get lazy loading for your child collection two requirements must be fulfilled:

    • The parent entity must be attached to an EF context
    • Your parent entity must be a lazy loading proxy

    Both requirements are met if you load the parent entity from the database through a context (and your navigation properties are virtual to allow proxy creation).

    If you don’t load the entity from the database but create it manually you can achieve the same by using the appropriate EF functions:

    var parent = context.TestParents.Create();
    parent.TestParentID = 1;
    context.TestParents.Attach(parent);
    

    Using Create and not new is important here because it creates the required lazy loading proxy. You can then access the child collection and the children of parent with ID = 1 will be loaded lazily:

    var children = parent.TestChildren; // no NullReferenceException
    

    Now, the default modelbinder has no clue about those specific EF functions and will simply instantiate the parent with new and also doesn’t attach it to any context. Both requirements are not fulfilled and lazy loading cannot work.

    You could write your own model binder to create the instance with Create() but this is probably the worst solution as it would make your view layer very EF dependent.

    If you need the child collection after model binding I would in this case load it via explicit loading:

    // parent comes as parameter from POST action method
    context.TestParents.Attach(parent);
    context.Entry(parent).Collection(p => p.TestChildren).Load();
    

    If your context and EF is hidden behind a repository you will need a new repository method for this, like:

    void LoadNavigationCollection<TElement>(T entity,
        Expression<Func<T, ICollection<TElement>>> navigationProperty) 
        where TElement : class
    {
        _context.Set<T>().Attach(entity);
        _context.Entry(entity).Collection(navigationProperty).Load();
    }
    

    …where _context is a member of the repository class.

    But the better way, as Darin mentioned, is to bind ViewModels and then map them to your entities as needed. Then you would have the option to instantiate the entities with Create().

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

Sidebar

Related Questions

We're building an app, our first using Rails 3, and we're having to build
I am using Paperclip to handle profile photo uploads in my app. They upload
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I used javascript for loading a picture on my website depending on which small
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
public static bool CheckLogin(string Username, string Password, bool AutoLogin) { bool LoginSuccessful; // Trim

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.