'Autoincrement Int Id not inserted on related items

Normally I use Guid's as Id's, but in this project I have to use int Id's, so my experience here is a little sparse.

My problem is that my autoincremental int Id's don't get a value OnAdd, that I can use on related items before I save changes.

Example:

var box = new Box
{
   Name = "Some name"
}
_dbContext.Add(box);

var boxItem = new BoxItem
{
    BoxId = box.Id, // This will be 0 on save
    Name = "Some other name"
}
_dbContext.Add(boxItem);

await _dbContext.SaveChangesAsync();

When I look in my database after the save, the boxItem.BoxId is 0. When working with Guid's that would've got the Box.Id generated value.

The models:

public class Box
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }

    public IList<BoxItem> BoxItems { get; set; }

}

public class BoxItem
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public int BoxId { get; set; }
    public string Name { get; set; }

}

The Id-column has "Identity specification" / "Is identity" = yes and "Identity increment" = 1 in the MSSQL-database.

I don't know if this is a limitation when working with int Id's, or my setup is incorrect?



Solution 1:[1]

I don't know if this is the right approach, but I solved it using this way:

var box = new Box
{
   Name = "Some name"
}
box.BoxItems = new List<BoxItem>(); // Line added

var boxItem = new BoxItem
{
    BoxId = box.Id,
    Name = "Some other name"
}
box.BoxItems.Add(boxItem);

_dbContext.Add(box); // Adding the box here with box.BoxItems instead

await _dbContext.SaveChangesAsync();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1