简体   繁体   English

实体框架在实例化新实体时生成索引错误

[英]Entity Framework generating index error when instantiating new entity

To contextualize my problem I am using C # VS 2017 + EF 6 (DB First) + SQL Server.为了解决我的问题,我使用 C# VS 2017 + EF 6 (DB First) + SQL Server。

Please let me explain the problem: I am instantiating a class to add a record to it.请让我解释一下这个问题:我正在实例化一个类以向其中添加一条记录。 However, in this particular class, when I instantiate, I immediately get an index error out of range.然而,在这个特定的类中,当我实例化时,我立即得到一个超出范围的索引错误。 It is an error of type System.ArgumentOutOfRangeException .这是System.ArgumentOutOfRangeException类型的错误。

Details:细节:

  1. I didn't add values, just instantiated the entity.我没有添加值,只是实例化了实体。
  2. For testing purposes I removed all relationships from the table involved and the problem continues.出于测试目的,我从所涉及的表中删除了所有关系,问题仍然存在。
  3. I already deleted the table and recreated it in both SQL and EDMX.我已经删除了该表并在 SQL 和 EDMX 中重新创建了它。

Has anyone ever experienced this?有没有人经历过这种情况? Any suggestions?有什么建议?

My code:我的代码:

     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; }
    }
}

To isolate the problem, try assigning a hard coded value first and see if it the error goes away:要隔离问题,请先尝试分配一个硬编码值,然后查看错误是否消失:

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

As mentioned in the comments in your post, the following line is most probably the culprit:正如您帖子中的评论所述,以下行很可能是罪魁祸首:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM