McGuireV10
McGuireV10

Reputation: 9936

Entity Framework 4.1 doesn't load relationships after SaveChanges?

I'm relatively new to EF. It appears that related table data isn't available after I call SaveChanges.

Let's say that I have a database with the following tables: User, Feature, and FeatureUser. FeatureUser ties User and Feature records together. I have a method which accepts a Feature object and it populates a list with User.name values based on the FeatureUser table. This works fine:

using (var db = new projectModel())
{
  feature f = db.features.First();
  populateList(f);
}

private void populateList(feature f)
{
  foreach(featureuser fu in f.featureusers)
    addToList(fu.user.name);
}

The important point in the code above is that I get back to the User.name value via the FeatureUser table's built-in link back to the User table. What doesn't work is to create new FeatureUser records, then save them, then attempt to follow that same process:

using (var db = new projectModel())
{
  feature f = db.features.First();
  foreach(int newuserid in somearray)
  {
    featureuser nfu = new featureuser();
    nfu.featureid = f.id;
    nfu.userid = newuserid;
    f.featureusers.add(nfu);
  }
  db.SaveChanges();
  populateList(f); // null reference error on fu.user.name
}

Is there a way to tell EF to resolve all those handy built-in relationship collections once I've established and saved the foreign keys needed to create the relationships?

Upvotes: 2

Views: 1538

Answers (1)

Eranga
Eranga

Reputation: 32447

The entity instances returned by EF are actually proxies. They contain logic to lazy load the navigational properties. But when you new up instance of featureuser it does not have that logic because it does not have that lazy loading logic.

Hence let EF create a proxy instance instead.

  foreach(int newuserid in somearray)
  {
    //create proxy instance
    var nfu = db.featureusers.Create();

    nfu.featureid = f.id;
    nfu.userid = newuserid;
    f.featureusers.add(nfu);
  }

Upvotes: 9

Related Questions