0

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?

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
Mads
  • 385
  • 1
  • 5
  • 18
  • 1
    `_dbContext.Add(box);` does not write the data to the database and generate the ID. `dbContext.SaveChangesAsync();` will write the data and generate value for autoincrement ID. – Chetan Jun 18 '21 at 09:10
  • @ChetanRanpariya so I have to call SaveChanges after _dbContext.Add(box) and again after _dbContext.Add(boxItem) ? I know my setup would work with Guid's, but is that different with int Id's? – Mads Jun 18 '21 at 09:18
  • You can either call `SaveChanges` twice or map the entities correctly in EF. https://stackoverflow.com/questions/6922690/how-to-map-child-entity-to-parent-entity-without-introducing-primitive-type-pare – Chetan Jun 18 '21 at 09:22
  • @ChetanRanpariya I would like not to call SaveChanges twice. But I don't see how my convention based entities are not mapped correctly? – Mads Jun 18 '21 at 09:25

1 Answers1

0

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();
Mads
  • 385
  • 1
  • 5
  • 18