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:
-
Attach()reward to the context so thatCampaigncan be lazily loaded (loaded when accessed)context.Rewards.Attach(reward);Note: You will only be able to lazy load
reward.Campaignwithin the context’s scope so if you’re not going to access any properties within the context lifespan, use option 2 or 3. -
Manually
Load()theCampaignpropertycontext.Entry(reward).Reference(c => c.Campaign).Load();Or if
Campaignwas a collection, for exampleCampaigns:context.Entry(reward).Collection(c => c.Campaigns).Load(); -
Manually
Include()theCampaignpropertyreward = context.Rewards.Include("Campaigns") .SingleOrDefault(r => r.Id == reward.Id);Although, I’d suggest
Loadsince you already haverewardin memory.
Check out the Loading Related Objects Section on this msdn doc for more information.