首页 > 解决方案 > Autoincrement 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 数据库中具有“身份规范”/“是身份”= yes 和“身份增量”= 1。

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

标签: c#sql-serverentity-framework-coreasp.net-core-5.0ef-core-5.0

解决方案


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

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

推荐阅读