停止ef-core将引用的记录插入到主表中

时间:2019-06-14 03:03:04

标签: c# asp.net-core ef-code-first entity-framework-core ef-core-2.1

我的设置如下。

  1. Supermaster具有Master的集合。
  2. Master具有对Reference PK ID的FK引用
  3. Reference表具有只读参考数据。

在ef代码中,当我从Supermaster表中加载记录时,我会根据某些条件向每个reference中添加Master

提交Supermaster时,我希望SupermasterMaster一起保存,并与所有Reference一起保存。

但是在dbContext.SaveChanges()上,EF尝试将记录插入到Reference中,但由于PK约束而失败。

到目前为止我一直在尝试什么

我尝试使用Fluent API与外键建立一对一关系。

我在保存上下文之前尝试过分离实体

_context.Entry(programmingRecord.ProgrammingRecordParameters.Select(x=>x.ValidationRule)).State = EntityState.Detached;

这是代码。

实体

Public class Supermaster
{
    public virtual ICollection<Master> ProgrammingRecordParameters { get; set; }
}

   public class Reference
    {
        public int Id { get; set; }
        public string Description { get; set; }
    }


   public class Master
    {
        public int Id { get; set; }
        public string DataGroup { get; set; }
        [ForeignKey("ValidationRuleId")]
        public Reference ValidationRule { get; set; }
        public int? ValidationRuleId { get; set; }
    }

API

    private void AddParameter(
            Supermaster rec,
            Master programmableParameter)
        {
            var param = new Master
            {                
                DataGroup = programmableParameter.DataGroup,
                ValidationRule = _context.References.FirstOrDefault(x=>x.Description==programmableParameter.DataGroup
            };

            rec.ProgrammingRecordParameters.Add(param);
        }

        public IActionResult PostProgrammingRecord([FromBody] Master programmingRecord)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }


            var repo = new ProgrammingRepository(_context);
            _context.ProgrammingRecords.Add(programmingRecord);
                _context.SaveChanges();
       }     

以下是错误堆栈

  HResult=0x80131500
  Message=An error occurred while updating the entries. See the inner exception for details.
  Source=Microsoft.EntityFrameworkCore.Relational
  StackTrace:
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(DbContext _, ValueTuple`2 parameters)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList`1 entries)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
   at RadioTMS.Web.Controllers.API.ProgrammingController.PostProgrammingRecord(ProgrammingRecord programmingRecord) in D:\TMS_Git_Repo\radio-tms\RadioTMS.Web\Controllers\API\ProgrammingController.cs:line 181
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()

Inner Exception 1:
SqlException: Cannot insert explicit value for identity column in table 'ValidationRules' when IDENTITY_INSERT is set to OFF.

1 个答案:

答案 0 :(得分:0)

EF试图在引用表中插入记录,因为实体上下文未加载引用数据。您应在调用保存更改之前获取上下文中加载的引用记录。