stoping ef-core to insert referenced record in to master table

0

I have a setup as follows.

  1. Supermaster has a collection of Master.
  2. Master having FK reference to Reference PK Id
  3. Reference table has readonly reference data.

In ef code when i load records from Supermaster table i add reference to each Master based on some condition.

on submission of Supermaster i expect Supermaster to be saved with all Master with reference to Reference.

But on dbContext.SaveChanges() EF tries to insert record to Reference and fails with PK constrain.

What i have tried till now

I have tried creating one to one relationship with foreign Key using Fluent API.

I have tried Detaching Entity before saving the context

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

.

Here is code.

Entity

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();
       }     

Following is the Error stack

  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.

c#
asp.net-core
ef-code-first
entity-framework-core
ef-core-2.1
asked on Stack Overflow Jun 14, 2019 by SKDesai • edited Jun 14, 2019 by SKDesai

1 Answer

0

EF is trying to insert record in reference table because entity context does not have reference data loaded.You should get record of reference loaded in context before calling save changes.

answered on Stack Overflow Jun 14, 2019 by SmartCoder

User contributions licensed under CC BY-SA 3.0