【发布时间】:2019-12-06 20:06:33
【问题描述】:
为了解决我的问题,我使用 C# VS 2017 + EF 6(DB First)+ SQL Server。
请让我解释一下问题:我正在实例化一个类以向其添加记录。但是,在这个特定的类中,当我实例化时,我立即得到一个超出范围的索引错误。这是System.ArgumentOutOfRangeException 类型的错误。
详情:
- 我没有添加值,只是实例化了实体。
- 出于测试目的,我从相关表中删除了所有关系,但问题仍然存在。
- 我已经删除了该表并在 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