无法为标识列插入显式值 - 进入相关表

时间:2018-04-13 15:04:57

标签: entity-framework-core

我有一个数据库第一个模型。

Database Diagram(Partial)

我的应用程序UI提供了一组复选框,每个复选框对应Data_Type中的每个值。

当用户检查一个时,我希望在BUS_APPL_DATA_TYPE中添加一行, 但是我收到一个关于无法在DATA_TYPE中为标识列插入显式值的错误(我绝对不想在此表中插入数据)

我的BUS_APPL的EF Model类具有此属性

public ICollection<BusApplDataType> BusApplDataType { get; set; }

那个EF Model类看起来像

public partial class BusApplDataType
{
    public int BusApplId { get; set; }
    public int DataTypeId { get; set; }

    [Newtonsoft.Json.JsonIgnore]
    public BusAppl BusAppl { get; set; }
    public DataType DataType { get; set; }
}

我究竟需要添加到BusApplDataType集合以获取要在BUS_APPL_DATA_TYPE中插入的记录?

编辑: 在SaveChanges之前的断点处。 索引2处的项目是现有项目,不会产生任何问题。 索引3处的项目是新的。没有这一切,一切都很好。数据库中有一个ID为5的DATA_TYPE。

enter image description here

周围的代码,如果它有帮助。

    [HttpPut("{id}")]
    public IActionResult Update(int id, [FromBody] BusAppl item)
    {
       ...
       var existing = _context.BusAppl.FirstOrDefault(t => t.Id == id);
       ...
       existing.BusApplDataType = item.BusApplDataType; //A bunch of lines like this, only this one causes any issue.
       ...
       _context.BusAppl.Update(existing);
       _context.SaveChanges();
       return new NoContentResult();
    }

1 个答案:

答案 0 :(得分:0)

我的问题是我需要使用我的上下文来查找实际的实体,使用传递的信息,而不是使用具有直接传递到我的api的所有相同值的那个。