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?