Not clear without seeing your model, but the general trick is to use the navigation properties to associate the two entities. Entity Framework will then be able to automatically update the foreign key property with the generated ID of the inserted parent records.
The canonical example:
public class Blog
{
public int Id { get; set; }
public string Title { get; set; }
public IList<Post> Posts { get; set; }
}
public class Post
{
public int Id { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
public string Title { get; set; }
}
context.Blogs.Add(new Blog
{
Title = "New Blog",
Posts = new List<Post>
{
new Post { Title = "Post 1" },
new Post { Title = "Another Post" },
},
});
context.SaveChanges();
Both
Post
instances will have the correct
BlogId
set when they are saved, even though the value isn't known until the
Blog
has been saved.