【问题标题】:Autoincrement Int Id not inserted on related itemsAutoincrement Int Id 未插入相关项目
【发布时间】:2021-06-18 09:07:57
【问题描述】:

通常我使用 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 时的限制,还是我的设置不正确?

【问题讨论】:

  • _dbContext.Add(box); 不会将数据写入数据库并生成 ID。 dbContext.SaveChangesAsync(); 将写入数据并为自增 ID 生成值。
  • @ChetanRanpariya 所以我必须在 _dbContext.Add(box) 之后调用 SaveChanges 并在 _dbContext.Add(boxItem) 之后再次调用?我知道我的设置适用于 Guid,但与 int Id 有区别吗?
  • 您可以调用SaveChanges 两次或在EF 中正确映射实体。 stackoverflow.com/questions/6922690/…
  • @ChetanRanpariya 我不想调用 SaveChanges 两次。但我没有看到我的基于约定的实体如何未正确映射?

标签: c# sql-server entity-framework-core asp.net-core-5.0 ef-core-5.0


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-10-08
    • 2012-06-03
    • 2023-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    相关资源
    最近更新 更多