Search code examples
c#entity-frameworkef-code-firstnavigation-properties

Is it necessary to lookup entity first to populate navigation property of another entity before saving it?


Previously I was saving a user this way:

context.User.Add(
  new User
  {
      GroupId = groupId
  });
await context.SaveChangesAsync()

But then introduced a navigation property for Group so save it now this way:

context.User.Add(
  new User
  {
      Group = await db.Groups.FindAsync(groupId)
  });
await context.SaveChangesAsync()

Is it possible to avoid this db lookup for each navigation property before saving the parent object? Like this:

context.User.Add(
  new User
  {
      Group = new Group { GroupId = groupId }
  });
await context.SaveChangesAsync()

It throws an entity validation exception:

Cannot insert the value NULL into column 'name', table 'Project.dbo.Groups'; column does not allow nulls. INSERT fails. The statement has been terminated.

So I'm wondering is there any workarounds


Solution

  • You should be able to just keep it the way you had before.

    context.User.Add(
      new User
      {
          GroupId = groupId
      });
    await context.SaveChangesAsync();
    

    If you step through your original code, you will notice the navigational property will be available (via lazy load) after you SaveChanges.