借口 - 但我真的需要帮助。
我需要更新一个具有另一个实体集合的实体(Db中的1对多关系),但是当我尝试更新主实体时,我最终遇到此错误:
System.Data.SqlClient.SqlException:当IDENTITY_INSERT设置为OFF时,无法在表'CustomProperties'中为identity列插入显式值。
我正在使用项目模板“Aspnetboilerplate”并使用它们的功能来更新实体。
这是我的“主要”类/实体,名为“Mockup”:
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也没有任何问题但是当我尝试更新集合时(在删除Collection中的一些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实体= await GetEntityByIdAsync(input.Id);包括在内。所以你重写方法添加一个包,它应该工作。
我们保持联系 ;)
问题是你有一个自定义属性:
JsonElementId
!= 0,ANDAdded
(可能)我不知道这是怎么发生的。
但JsonElementId
可能配置为IDENTITY
。那是他的值是由db计算的。因此,如果你向db提供一个值,db就会抱怨,除非你SET IDENTITY_INSERT OFF
,如果你要求db授权设置值(这里不推荐)。
所以你必须找到你的CustomProperty为什么:
Unchanged
州,或