c# - 实体框架在实例化新实体时生成索引错误
问题描述
为了将我的问题上下文化,我使用的是 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; }
}
}
解决方案
要隔离问题,请先尝试分配一个硬编码值,然后查看错误是否消失:
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);
推荐阅读
- vector - 基于其他向量值的数学计算在 R 中填充新向量
- wordpress - 将 Bootstrap 4 JS 导入项目
- javascript - 智能在 VS Code 中不适用于 Gsap
- python - 从 R 的 system() 调用 python:找不到熊猫
- python - 使用 ElementTree 从 XML 中获取值
- javascript - 在多构建 Vue js 应用程序中定义多个配置的最佳方法是什么?
- html - 使用 HTML 和 css 使整个形状可点击
- python - 尝试使用 tkinter 网格创建数独游戏,GUI 网格出现问题
- javascript - 如何计算动画 gif 循环的次数并在 javascript 中显示该计数?
- android - 获取 java.io.IOException:当我从一个片段导航到另一个片段时取消