繁体   English   中英

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

[英]stoping ef-core to insert referenced record in to master table

我有如下设置。

  1. Supermaster Master有一个Master的集合。
  2. Master参与Reference PK Id的FK参考
  3. Reference表具有只读参考数据。

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

在提交Supermaster我希望Supermaster与所有Master一起参考Reference

但是在dbContext.SaveChanges() EF尝试将记录插入Reference并且使用PK约束失败。

我到现在为止做了什么

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

我在保存上下文之前尝试过Detaching Entity

_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.

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM