c# - EF 核心 : Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF on one to many

标签 c# entity-framework-core ef-fluent-api

我将 EF Core 与 ASP NET Core 一起用于我的服务器,当我尝试更新数据库中的现有值时,我收到以下错误:

Cannot insert explicit value for identity column in table 'TeambuildingType' when IDENTITY_INSERT is set to OFF.

我正在做的是:

  1. 创建一个 Teambuilding 元素,最初将 TeamBuildingTypeId 的外键设置为 NULL

  2. 使用 INSERT INTO... 直接从 SQL Management Studio 创建两个 TeambuildingType。(Teambuilding 和 TeambuildingType 的 Id 自动递增)

  3. 尝试通过像这样添加 TeambuildingTypeId 来更新现有的 Teambuilding:team.TeambuildingTypeId = 1 或 team.Type =(从同一上下文中的数据库中获取的对象)

  4. 在捕获中接收到来自上面的错误

这是我的代码:

团队 build .cs

public class TeamBuilding
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public double? TargetBudget { get; set; }

    public TeambuildingStatus? Status { get; set; }

    public int? TeambuildingTypeId { get; set; }

    public virtual TeambuildingType Type { get; set; }

    public int? LocationId { get; set; }

    public virtual Location Location { get; set; }

    public virtual ICollection<Participant> Participants { get; set; }

    public virtual ICollection<Room> Rooms { get; set; }

    public int TimePollId { get; set; }

    public virtual TimePoll TimePoll { get; set; }
}

TeambuildingType.cs

public class TeambuildingType
{
    [Key]
    public int Id { get; set; }

    public string Type { get; set; }

    public virtual ICollection<TeamBuilding> Teambuildings { get; set; }
}

TeamBuildingForUpdateDto.cs

public class TeamBuildingForUpdateDto
{
    [Required]
    public int Id { get; set; }
    public string Title { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime StartDate { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime EndDate { get; set; }
    public LocationViewModel Location { get; set; }
    public TeambuildingStatus Status { get; set; }
    public double TargetBudget { get; set; }
    public TeamBuildingTypeDto Type { get; set; }
}

更新 Controller 方法:

    [HttpPut]
    public IActionResult UpdateTeamBuilding([FromBody]TeamBuildingForUpdateDto teamBuildingForUpdateDto)
    {
        try
        {
            var existingTeamBuilding = _service.GetByID(teamBuildingForUpdateDto.Id);
            if (existingTeamBuilding == null)
            {
                return NotFound("There is no team buiding with such an ID");
            }

            _service.UpdateTeamBuilding(teamBuildingForUpdateDto);
            return Ok();
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

服务方式:

    public TeamBuildingForUpdateDto UpdateTeamBuilding(TeamBuildingForUpdateDto teamBuildingDto)
    {
        var teamBuilding = _repositoryTeam.GetByID(teamBuildingDto.Id);
        var type = _repositoryType.GetByID(teamBuildingDto.Type.Id);
        Mapper.Map(teamBuildingDto.Type, type);
        Mapper.Map(teamBuildingDto, teamBuilding);

        teamBuilding.Type = type;
        //OR
        //teamBuilding.TeambuildingTypeId = type.Id;
        //Neither from above works

        _repositoryTeam.Edit(teamBuilding);
        _repositoryTeam.Commit();
        return teamBuildingDto;
    }

使用 Fluent API 的上下文:

            modelBuilder.Entity<Models.TeamBuilding>()
            .HasOne(t => t.Type)
            .WithMany(ty => ty.Teambuildings)
            .HasForeignKey(t => t.TeambuildingTypeId);

            modelBuilder.Entity<TeambuildingType>().ToTable("TeambuildingType");
            modelBuilder.Entity<Models.TeamBuilding>().ToTable("TeamBuilding");


        public DbSet<TeambuildingType> TeambuildingTypes { get; set; }
        public DbSet<Models.TeamBuilding> TeamBuildings { get; set; }

我也没有仅在这些模型上收到此错误,我在使用 FK 的任何东西上以及我尝试在其中插入新值的地方收到相同的错误。

TeamBuilding和TeambuildingType之间是一对多的关系

我做错了什么?

最佳答案

我解决了这个问题。根据 mcbowes 的建议,我检查了 AutoMapper 和我从服务器发送的内容,我看到我试图在我的 TeamBuilding Type 字段中分配一个 TeamBuildingType,然后尝试进行更新。

我通过不将任何 TeamBuildingType 分配给 Type 字段(使其为空)并仅将 TeamBuildingType 主键分配给 TeambuildingTypeId 字段来解决该问题。现在它进行更新。

感谢 mcbowes 的建议。

关于c# - EF 核心 : Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF on one to many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51724101/

相关文章:

c# - 从 3.1.2 版升级到 5.0.3 版后,Entity Framework 核心 Include() 不起作用

c# - Mvc,外键关系

entity-framework - EF6 阻止不在外键上创建索引

c# - T[] 是否实现了 IList<T>?

c# - Observable.Delay 或 Observable.Buffer 重用同一线程

c# - EntityFramework核心(七)如何映射protected/private属性

entity-framework - 与 EF 6 一起部署 Entity Framework Core 2.0?

c# - 从通用列表中选择底部 N

c# - 通过找到最少的重复来优化思维导图

c# - Entity Framework 中同一类的多个列表