0

When I add an a new entity to a table I would want to populate the navigation properties after saving the changes. How would I do this?

Here's what I'm doing now, and the navigation property Condition is null. I have checked that the foreign key has been set. I also tried just assigning to the nav property manually by reading from the other table directly but even that did not work.

...
var group = _context.Groups.AddRange(groups).First();
await _context.SaveChangesAsync();
// group.Condition which is a navigation property is null after this. 
// The property does work when I get the group from the context, after adding.
2
  • Have you tried var group = _context.Groups.AddRange(groups).First().Include(x=>x.Condition); Commented Jun 5, 2014 at 14:53
  • That doesn't work, can't even use Include there. Doing an update of the entity where I use Include after saving did it. Commented Jun 5, 2014 at 15:46

2 Answers 2

4

This will be the case when lazy loading is disabled. Enable it by adding virtual keyword to the properties. You can also use eager loading by using _context.Groups.Include("Condition")

You can get details from similar question Navigation property returns null after inserting

Sign up to request clarification or add additional context in comments.

1 Comment

The property was already marked virtual. I got it to work by looking at your link though. Include did it, however I had to update the entity after saving.
0

Here's how I got it to work by checking the link provided by Ankit Sinha:

var group = _context.Groups.AddRange(groups).First();
await _context.SaveChangesAsync();
var group = _context.Groups.Include(x => x.Condition).SingleOrDefaultAsync(x => x.Id == group.id);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.