JuhaKangas
JuhaKangas

Reputation: 883

Entity Framework navigation property not set when adding entity

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.

Upvotes: 0

Views: 1198

Answers (2)

JuhaKangas
JuhaKangas

Reputation: 883

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);

Upvotes: 0

Ankit Sinha
Ankit Sinha

Reputation: 421

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

Upvotes: 4

Related Questions