【发布时间】:2021-08-25 14:41:36
【问题描述】:
我在“Items”和“Itemattributes”表之间的数据库上创建了一个新的多对多关系。
型号:
Item.cs
public class Item
{
[Key]
public int ItemCode { get; set; }
public string ItemName { get; set; }
public ICollection<ItemAttribute> ItemAttributes { get; set; }
}
ItemAttribute.cs
public class ItemAttribute
{
[Key]
public int ItemAttributeCode { get; set; }
public string Title { get; set; }
public ICollection<Item> Items { get; set; }
}
数据上下文
public DbSet<Item> Items { get; set; }
public DbSet<ItemAttribute> ItemAttributes { get; set; }
在包管理器控制台中使用命令:
Add-Migration FunnyNameForMigration
Update-Database
实体框架创建一个表来连接“Items”和“ItemAttributes”表,“ItemsItemAttributes”。 当我尝试使用 ItemController 创建具有 2 个 ItemAttributes 的新项目时:
[HttpPost]
public async Task<IActionResult> Post([Bind("ItemCode")] Item item)
{
_context.Items.Add(item);
await _context.SaveChangesAsync();
return Ok(item.ItemCode);
}
我得到错误:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'ItemAttributes' when IDENTITY_INSERT is set to OFF.
我猜到 Item / Itemattribute 关系只在新的“ItemsItemAttributes”表上,为什么 Entity Framework 试图在“Itemattribute”表上添加一些东西?以及如何使用 ItemAttributes 添加新项目?
更新
当我在表“ItemItemattribute”中手动插入表“Item”和“Itemattribute”之间的新连接时,它工作正常。我怀疑实体框架的自动插入有问题。
【问题讨论】:
-
请公开 Item 和 ItemAttribute 的所有类以及您发送到 Post 操作的内容
-
您是否在 Db 上下文的 OnModelCreating 方法中添加了多对多关系?另外,正如 Nicola 所说,请向我们展示您的模型和 DbContext 的完整代码以及您如何发布项目。
-
@NicolaBiada 我添加了类中缺少的部分,我只向控制器发送了一个我创建的新项目对象
-
@MajdOdeh 我没有对 OnModelCreating 方法做任何事情
标签: c# entity-framework asp.net-core blazor