首页 > 解决方案 > 实体框架在实例化新实体时生成索引错误

问题描述

为了将我的问题上下文化,我使用的是 C# VS 2017 + EF 6(DB First)+ SQL Server。

请让我解释一下这个问题:我正在实例化一个类来添加一条记录。但是,在这个特定的类中,当我实例化时,我立即得到一个超出范围的索引错误。这是一个类型的错误System.ArgumentOutOfRangeException

细节:

  1. 我没有添加值,只是实例化了实体。
  2. 出于测试目的,我从所涉及的表中删除了所有关系,问题仍然存在。
  3. 我已经删除了该表并在 SQL 和 EDMX 中重新创建了它。

有没有人经历过这个?有什么建议么?

我的代码:

     using (coletasEntities ctx = new coletasEntities())
     {
           // error happens on line below
           coleta_nota_problema erro = new coleta_nota_problema();

           erro.descricao = msg.Substring(0, 250);
           erro.id_coleta_nota = id;

           ctx.coleta_nota_problema.Add(erro);
           ctx.SaveChanges();
     }

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Coletas
{
    using System;
    using System.Collections.Generic;

    public partial class coleta_nota_problema
    {
        public int id_coleta_nota_problema { get; set; }
        public int id_coleta_nota { get; set; }
        public string descricao { get; set; }
    }
}

标签: c#visual-studioentity-framework

解决方案


要隔离问题,请先尝试分配一个硬编码值,然后查看错误是否消失:

erro.descricao = "hello"; // any arbitrary text
erro.id_coleta_nota = 1000; // any arbitrary integer unique if this is the key
erro.id_coleta_nota_problema = 1000; // any arbitrary integer

正如您帖子中的评论所述,以下行很可能是罪魁祸首:

erro.descricao = msg.Substring(0, 250);

推荐阅读