未在相关项上插入自动递增Int Id



通常我使用Guid作为Id,但在这个项目中,我必须使用int Id,所以我在这里的经验有点稀疏。

我的问题是,我的自动增量int Id没有获得值OnAdd,在保存更改之前,我可以在相关项目上使用该值。

示例:

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();

保存后在数据库中查找时,boxItem.BoxId为0。当使用Guid时,会得到Box.Id生成的值。

型号:

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; }
}

Id列具有";标识规范"/"是身份是和"是";标识增量"=MSSQL数据库中的1。

我不知道这是使用int Id时的限制,还是我的设置不正确?

我不知道这是否是正确的方法,但我用这种方法解决了它:

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();

最新更新