C# 将1更新为多导航属性时出错

C# 将1更新为多导航属性时出错,c#,asp.net,sql-server,entity-framework,aspnetboilerplate,C#,Asp.net,Sql Server,Entity Framework,Aspnetboilerplate,对不起,我真的需要帮助 我需要更新具有另一个实体集合的实体(Db中的1对多关系),但当我尝试更新主实体时,我最终出现以下错误: System.Data.SqlClient.SqlException:当identity_insert设置为OFF时,无法在表“CustomProperties”中为identity列插入显式值 我正在使用项目模板“Aspnetboilerplate”,并使用它们的函数来更新实体 这是我的“主要”类/实体,称为“模型”: 当我为新实体执行此操作时,它在Db中创建实体模型

对不起,我真的需要帮助

我需要更新具有另一个实体集合的实体(Db中的1对多关系),但当我尝试更新主实体时,我最终出现以下错误:

System.Data.SqlClient.SqlException:当identity_insert设置为OFF时,无法在表“CustomProperties”中为identity列插入显式值

我正在使用项目模板“Aspnetboilerplate”,并使用它们的函数来更新实体

这是我的“主要”类/实体,称为“模型”:


当我为新实体执行此操作时,它在Db中创建实体模型和CustomProperties也没有任何问题,但是当我尝试更新集合(在集合中删除一些CustomProperties后)时,我出现了错误。

我认为问题出在默认方法AsyncCrudAppService中。如果你看 更新方法: `公共虚拟异步任务更新(TUpdateInput) { CheckUpdatePermission()

实体加载时没有包含任何内容,因此实体框架正在尝试插入导航属性中包含的元素,但它们已经存在,然后出现错误

您应该找到一种方法来访问var entity=await GetEntityByIdAsync(input.Id);以及include。 因此,您重写了添加include的方法,它应该可以工作


我们保持联系;)

问题是您有一个自定义属性:

  • JsonElementId
    !=0、
  • an=
    添加了
    (可能)
我不知道这是怎么发生的

但是
JsonElementId
可能配置为
IDENTITY
。这是由db计算的值。因此,如果您向db提供一个值,db会投诉,除非您
设置IDENTITY\u INSERT OFF
,即如果您请求db授权设置该值(此处不推荐)

因此,您必须找到您的CustomProperty的原因:

  • 未处于未更改的状态,或
  • 获取非0密钥

将代码张贴在要插入的位置/update@TheOne好的,我在下面贴了一个例子:)下面的部分是关于答案的,请编辑你的问题并包括所有附加信息好的,完成@TheOne
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; }
}
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; }
}
{
    "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
    }
}
        var entity = await GetEntityByIdAsync(input.Id);

        MapToEntity(input, entity);
        await CurrentUnitOfWork.SaveChangesAsync();

        return MapToEntityDto(entity);
    }`