Get entity navigation properties after insert

C#Entity FrameworkEntity Framework-6

C# Problem Overview


I have the following 2 classes:

public class Reward 
{
    public int Id { get; set; }
    public int CampaignId { get; set;
    public virtual Campaign Campaign { get; set; }
}

public class Campaign 
{
    public int Id { get; set; }
    public virtual ICollection<Reward> Rewards { get; set; }
}

With this I have all the obvious necessary stuff like a DbContext and mappings.

Now let's say I create a Reward entity and insert it like this:

var reward = new Reward { CampaignId = 1 };
context.Set<Reward>().Add(reward);
context.SaveChanges();

reward = context.Set<Reward>().SingleOrDefault(a => a.Id == reward.Id);
//reward.Campaign is null

I obviously have a campaign with Id 1 so the FK constraint is happy. After this insert, my reward entity has it's new Identity Id set. Now the problem is that reward is still just the Reward entity I created. And with this, the reward.Campaign property is null. It seems like EF is keeping the inserted entities in memory, and when I then do a .SingleOrDefault(a => a.Id == reward.Id) it simply returns the entity in memory, and not a new proxy. This is probably a good thing.

So the question is: How does one access or load the navigation properties after an insert or get a new proxy that has the navigation properties as proxies as well.

Am I perhaps inserting in the wrong way?

C# Solutions


Solution 1 - C#

If I understand you correctly, you're trying to eagerly load a complex property after establishing a relationship via a foreign key property.

SaveChanges() does not do anything in the way of loading complex properties. At most, it is going to set your primary key property if you're adding new objects.

Your line reward = context.Set<Reward>().SingleOrDefault(a => a.Id == reward.Id); also does nothing in the way of loading Campaign because your reward object is not attached to the context. You need to explicitly tell EF to load that complex object or attach it then let lazy loading work its magic.

So, after you context.SaveChanges(); you have three options for loading reward.Campaign:

  1. Attach() reward to the context so that Campaign can be lazily loaded (loaded when accessed)

     context.Rewards.Attach(reward);
    

    Note: You will only be able to lazy load reward.Campaign within the context's scope so if you're not going to access any properties within the context lifespan, use option 2 or 3.

  2. Manually Load() the Campaign property

     context.Entry(reward).Reference(c => c.Campaign).Load();
    

    Or if Campaign was a collection, for example Campaigns:

     context.Entry(reward).Collection(c => c.Campaigns).Load();
    
  3. Manually Include() the Campaign property

     reward = context.Rewards.Include("Campaigns")
         .SingleOrDefault(r => r.Id == reward.Id);
    

    Although, I'd suggest Load since you already have reward in memory.

Check out the Loading Related Objects Section on this msdn doc for more information.

Solution 2 - C#

As you are creating your reward object as new Reward(), EF doesn't have a proxy. Instead, create it using DbSet.Create like this:

var reward = context.Set<Reward>().Create();
reward.CampaignId = 5;
context.SaveChanges();

Next attach it to your DbSet:

context.Rewards.Attach(reward);

Finally, you can now use lazy loading to get related entities:

var campaign = reward.Campaign;

Solution 3 - C#

I have a simple Solution around the problem.

instead of adding the CampaignID to the reward, add the campaign Object.. so:

var _campaign = context.Campaign.First(c=>c.Id == 1);//how ever you get the '1'
var reward = new Reward { Campaign = _campaign };
context.Set<Reward>().Add(reward);
context.SaveChanges();

//reward.Campaign is not null

Entity framework does all the heavy lifting here.

You're probably thinking that it's a waste to load the entire Campaign object but if you are going to be using it (from what it looks like, seems you are) then I don't see why not. You can even use the include statement when fetching it above if you need to access navigation properties from the Campaign object...

var _campaign = context.Campaign.include(/*what ever you may require*/).First(c=>c.Id = 1);

Solution 4 - C#

In addition to Carrie Kendall and DavidG (in VB.NET):

Dim db As New MyEntities
Dim r As Reward = = db.Set(Of Reward)().Create()
r.CampaignId = 5
db.Reward.Add(r) ' Here was my problem, I was not adding to database and child did not load
db.SaveChanges()

Then, property r.Campaign is available

Solution 5 - C#

Did you try using Include()? Something like this:

reward = context.Set<Reward>().Include("Campaigns").SingleOrDefault(a => a.Id == reward.Id);

Solution 6 - C#

if you have more than one navigation properties or want to add more than one records it may be hard to do it in these ways.

so i suggest if the memory doesn't matter create a new context object after adding your records , and use it instead

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustus BurgerView Question on Stackoverflow
Solution 1 - C#Carrie KendallView Answer on Stackoverflow
Solution 2 - C#DavidGView Answer on Stackoverflow
Solution 3 - C#StevenView Answer on Stackoverflow
Solution 4 - C#DaniView Answer on Stackoverflow
Solution 5 - C#FloreminView Answer on Stackoverflow
Solution 6 - C#Hedayat Allah KamalianView Answer on Stackoverflow