【问题标题】:Entity Framework generating index error when instantiating new entity实体框架在实例化新实体时生成索引错误
【发布时间】:2019-12-06 20:06:33
【问题描述】:

为了解决我的问题,我使用 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; }
    }
}

【问题讨论】:

  • 我认为您的问题更有可能是致电Substring()。我猜msg 没那么长。
  • @Crowcoder,它肯定不是子字符串。错误发生在实体实例之后的行上,甚至没有处理序列行。如果我从 Substring 中删除该行,问题仍然存在。
  • OK,那我们能看到coelta_nota_problema的构造函数吗?
  • 异常的堆栈跟踪是什么?这个类很可能有一个部分扩展,它有一个带有违规代码的构造函数。
  • 您的课程中的 KEY 属性是什么?您还可以向我们展示您正在使用的数据(id 和 msg)。此外,您可以使用 DbContext.Database.Log 属性启用 DBContext 级别的日志记录,该属性记录所有进入数据库的 INSERT 语句。替代方案,您可以运行 sql profiler 并查看正在发送到数据库的 INSERT 语句

标签: c# visual-studio entity-framework


【解决方案1】:

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

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

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

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

【讨论】:

  • 我改行来修复错误:if (msg.lenth > 250) msg​​ = msg.substring(0,250)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多