c# - 将 1 更新为多个导航属性时出错
问题描述
原谅我,但我真的需要帮助。
我需要更新一个具有另一个实体集合的实体(Db 中的一对多关系),但是当我尝试更新主要实体时,我最终遇到了这个错误:
System.Data.SqlClient.SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“CustomProperties”中插入标识列的显式值。
我正在使用项目模板“Aspnetboilerplate”并使用它们的功能来更新实体。
这是我的“主要”类/实体,称为“样机”:
public class Mockup : FullAuditedEntity<int, User>
{
public string Name { get; set; }
public string Json { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string Support { get; set; }
public string Format { get; set; }
public ICollection<CustomProperty> CustomProperties { get; set; }
}
我想在上面更新“CustomProperties”集合。
这是我的 Customproperty 类/实体:
public class CustomProperty : FullAuditedEntity<int>
{
public int JsonElementId { get; set; }
public string Value { get; set; }
public CustomPropertyType Type { get; set; }
public Mockup Mockup { get; set; }
}
当我尝试进行更新时,我无法真正理解它为什么要尝试执行“IDENTITY_INSERT”以及如何以另一种方式进行。如何使我的更新正常工作?
这是我发布到 aspnetboilerplate 更新函数的 Json 示例。它由 Automapper 映射到上面发布的实体:
{
"name":"okok",
"json":"",
"width":827,
"height":1170,
"support":null,
"format":null,
"customProperties":[
{
"jsonElementId":949264,
"value":"150",
"type":0,
"id":3335
},
{
"jsonElementId":427781,
"value":"150",
"type":0,
"id":3336
},
{
"jsonElementId":165189,
"value":"366.99445670195036",
"type":0,
"id":3337
},
{
"jsonElementId":110359,
"value":"150",
"type":0,
"id":3338
},
{
"jsonElementId":342044,
"value":"150",
"type":0,
"id":3339
}
],
"id":8040
}
}
当我为新实体执行此操作时,它也在 Db 中创建 Mockup 实体和 CustomProperties 也没有任何问题,但是当我尝试更新集合时(在删除集合中的一些 CustomProperties 之后)我有错误。
解决方案
我认为问题出在默认方法 AsyncCrudAppService 中。如果您查看更新方法:`public virtual async Task Update(TUpdateInput input) { CheckUpdatePermission();
var entity = await GetEntityByIdAsync(input.Id);
MapToEntity(input, entity);
await CurrentUnitOfWork.SaveChangesAsync();
return MapToEntityDto(entity);
}`
实体在没有任何包含的情况下加载,因此实体框架正在尝试插入导航属性中包含的元素,但它们已经存在,那么您会遇到错误...
你应该找到一种方法来 var entity = await GetEntityByIdAsync(input.Id); 带有一个包含。因此,您覆盖该方法添加一个包含,它应该可以工作。
我们保持联系 ;)
推荐阅读
- java - 无论如何,您可以在 Apache POI 中删除表格行内的边框吗?
- list - Terraform:如何使用列表或地图在 azurerm 中配置多个存储容器?
- symfony - 必须安装 Zend-crypt 才能使用 zenstruck/form-bundle 中的 ajax_entity_controller
- excel - 用户表单在 excel 中仅显示 3 个命令按钮中的 1 个
- javascript - 在异步函数中同时进行 fetch(),并在使用 JavaScript 完成后返回
- javascript - 有没有更好的方法在 React 中导出多个命名函数?
- performance - 为什么在每个 clEnqueue 函数中都会调用 clGetPlatformInfo?
- c - 如何交换使用指向数组的指针定义的二维数组中的行?
- firebase - 如何在 vuetify 和 firebase 中使用 v-for 动态添加图像
- flask - Flask-Login 未注册用户给出 500 错误