使用EF插入数据数组时出现InvalidOperationException

时间:2018-10-22 08:38:22

标签: c# asp.net entity-framework

System.InvalidOperationException: 'The instance of entity type 'Borrower' cannot be 
tracked because another instance with the key value '{BorrowerId: -2147482647}' is
already being tracked. When attaching existing entities, ensure that only one 
entity instance with a given key value is attached.'

当我尝试使用实体框架将数据数组插入SQL Server时,会产生上述错误。

下面是我尝试插入到数据库中的JSON数组,该数组包含两个元素,并且我认为该错误是由于实体框架将两个数组元素以相同的ID插入数据库而引起的。如果我从数组中删除一个元素,那么数据将正常插入。正确插入单个元素的事实也表明问题不在于数据库中当前保存的数据。

"borrower": [
    {
      "borrowerId": 0,
      "address": {
        "addressId": 0,
        "houseNum": "string",
        "houseName": "string",
        "streetName": "string",
        "locality": "string",
        "town": "string",
        "county": "string",
        "postcode": "NE11NE"
      },
      "title": 1,
      "firstName": "string",
      "lastName": "string",
      "dob": "2018-10-17T09:22:00.422",
      "homeNumber": "01212122222",
      "workNumber": "01212122222",
      "mobileNumber": "01212122222",
      "email": "borrower@borrower.com"
    },
    {
      "borrowerId": 0,
      "address": {
        "addressId": 0,
        "houseNum": "string",
        "houseName": "string",
        "streetName": "string",
        "locality": "string",
        "town": "string",
        "county": "string",
        "postcode": "NE11NE"
      },
      "title": 1,
      "firstName": "string",
      "lastName": "string",
      "dob": "2018-10-17T09:22:00.422",
      "homeNumber": "01212122222",
      "workNumber": "01212122222",
      "mobileNumber": "01212122222",
      "email": "borrower@borrower.com"
    }
  ]

在这种情况下调用的方法相对简单,因此不应成为错误的根源,但为清楚起见,我在下面将其包括在内。

发送指令

[HttpPost]
        public IActionResult SendInstruction([FromBody]SolicitorInstruction si)
        {
            //Validate
            ValidationController controller = new ValidationController();
            bool instructionIsValid = controller.ValidateInstruction(si);

            if (instructionIsValid)
            {
                _instructionRepo.CreateInstruction(si);
                Console.WriteLine("\nInstruction successfully inserted into database records.\n");
                return Ok("Successfully added instruction into database.");
            }

            Console.WriteLine("\nInvalid Data: Insert into database records aborted.\n");
            return BadRequest(controller.ErrorMessages);
        }

创建说明

public void CreateInstruction(SolicitorInstruction instruction)
        {
            _context.SolicitorInstructions.Add(instruction);
            _context.SaveChanges();
        }

DbContext-用于创建EF模型。

public class SolicitorContext : DbContext
    {

        public DbSet<AdditionalInformation> AdditionalInformations { get; set; }
        public DbSet<Address> Addresses { get; set; }
        public DbSet<Borrower> Borrowers { get; set; }
        public DbSet<BorrowerBank> BorrowerBanks { get; set; }
        public DbSet<Broker> Brokers { get; set; }
        public DbSet<CurrentLender> CurrentLender { get; set; }
        public DbSet<Occupier> Occupiers { get; set; }
        public DbSet<Property> Properties { get; set; }
        public DbSet<Solicitor> Solicitors { get; set; }
        public DbSet<SolicitorInstruction> SolicitorInstructions { get; set; }

        public SolicitorContext(DbContextOptions<SolicitorContext> options)
            : base(options)
        {

        }

借款人表

[Table("Borrower")]
    public partial class Borrower
    {
        [Key]
        public int BorrowerId { get; set; }
        [ForeignKey("AddressId")]
        public Address Address { get; set; }
        //public bool BorrowerAddressIsCorrespondenceAddress { get; set; }
        public Honorifics Title { get; set; }
        [StringLength(32)]
        public string FirstName { get; set; }
        [StringLength(32)]
        public string LastName { get; set; }
        public DateTime Dob { get; set; }
        [StringLength(32)]
        public string HomeNumber { get; set; }
        [StringLength(32)]
        public string WorkNumber { get; set; }
        [StringLength(32)]
        public string MobileNumber { get; set; }
        [StringLength(64)]
        public string Email { get; set; }
    }

0 个答案:

没有答案