首页 > 解决方案 > 将 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 之后)我有错误。

标签: c#asp.netsql-serverentity-frameworkaspnetboilerplate

解决方案


我认为问题出在默认方法 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); 带有一个包含。因此,您覆盖该方法添加一个包含,它应该可以工作。

我们保持联系 ;)


推荐阅读