c# - 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 时的限制,或者我的设置不正确?
解决方案
我不知道这是否是正确的方法,但我用这种方式解决了它:
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();
推荐阅读
- entity-framework-core - 带有 2 个参数错误 System.InvalidOperationException 的 EF Core 存储过程:
- mysql - SQL排序总和两列
- java - Android:链接到导航抽屉中的 URL
- java - 将 TableColumn 对象连接到自定义类的问题
- c++ - GLSL 错误:计算着色器中未定义的布局缓冲区变量,尽管它已定义
- node.js - Node Express 身份验证/授权
- r - 尝试安装 R 4.0.1,但遇到 Ubuntu 问题
- c++ - DDS_Octet 位移问题:右移在 C++ 中添加 1 而不是 0
- linux - sigtimedwait() 的跨 (POSIX) 平台模拟
- react-native - 来自 React Native 中 Firebase Firestore 的重复数据