1

When I try to get data from the table Anexos, I get this Exeption:

"An error occurred while executing the command definition. See the inner exception for details."

"Invalid column name 'Empresas_Id'."

Then I was looking for the Empresas_Id field in my model. But..

public class Anexos
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Display(Name = "Descrição"), StringLength(150)]
    public string Descricao { get; set; }

    [StringLength(90)]
    public string Nome { get; set; }

    public string Caminho { get; set; }

    [Column("PessoaId")]
    public int? PessoaId { get; set; }

    [Column("Contrato_Id")]
    public int? ContratoId { get; set; }

    [Column("TipoDocumento_Id")]
    public int TipoDocumentoId { get; set; }

    [ForeignKey("ContratoId")]
    public virtual Contratos Contrato { get; set; }

    [ForeignKey("PessoaId")]
    public virtual Pessoas Pessoa { get; set; }

    [ForeignKey("TipoDocumentoId")]
    public virtual TipoDocumento TipoDocumento { get; set; }

}

There is no Empresas_Id field, then I checked my database table, but nothing there too... The Contratos model have the field, but I can take the data from it without errors. Is this a bug of EF ?

I checked this answers trying to find my issue:

Edit

My table Script :

CREATE TABLE [dbo].[Anexos] (
    [Id]               INT            IDENTITY (1, 1) NOT NULL,
    [Descricao]        NVARCHAR (150) NULL,
    [Nome]             NVARCHAR (90)  NULL,
    [Caminho]          NVARCHAR (MAX) NULL,
    [PessoaId]         INT            NULL,
    [Contrato_Id]      INT            NULL,
    [TipoDocumento_Id] INT            NOT NULL,
    CONSTRAINT [PK_dbo.Anexos] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_dbo.Anexos_dbo.Contratos_Contrato_Id] FOREIGN KEY ([Contrato_Id]) REFERENCES [dbo].[Contratos] ([Id]),
    CONSTRAINT [FK_dbo.Anexos_dbo.Pessoas_PessoaId] FOREIGN KEY ([PessoaId]) REFERENCES [dbo].[Pessoas] ([Id]),
    CONSTRAINT [FK_dbo.Anexos_dbo.TipoDocumento_TipoDocumento_Id] FOREIGN KEY ([TipoDocumento_Id]) REFERENCES [dbo].[TipoDocumento] ([Id])
);


GO
CREATE NONCLUSTERED INDEX [IX_PessoaId]
    ON [dbo].[Anexos]([PessoaId] ASC);


GO
CREATE NONCLUSTERED INDEX [IX_Contrato_Id]
    ON [dbo].[Anexos]([Contrato_Id] ASC);


GO
CREATE NONCLUSTERED INDEX [IX_TipoDocumento_Id]
    ON [dbo].[Anexos]([TipoDocumento_Id] ASC);

My connection string :

  <add name="DefaultConnection" connectionString="data source=PC-TREINA09\SQLEXPRESS;initial catalog=erp10_new;integrated security=True; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

Edit 2 :

The Contratos table:

public class Contratos
{
    public Contratos()
    {
        Items = new HashSet<ContratoItens>();
        Anexos = new HashSet<Anexos>();
        Contas = new HashSet<ContasContasReceber>();
    }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public int Numero { get; set; }

    public DateTime? DataContrato { get; set; }

    public DateTime? DataVenda { get; set; }

    public int? DiaDoMesCobranca { get; set; }

    public int? MesesVigencia { get; set; }

    public string Observacoes { get; set; }

    public TipoDesconto? TipoDesconto { get; set; }

    public double? ValorDesconto { get; set; }

    public double? ValorTotal { get; set; }

    public StatusContrato Status { get; set; }

    [Column("EmpresaId")]
    public int EmpresaId { get; set; }

    [Column("Cliente_Id")]
    public int ClienteId { get; set; }

    [Column("ClienteFaturamento_Id")]
    public int ClienteFaturamentoId { get; set; }

    [Column("Pagamento_Id")]
    public int? PagamentoId { get; set; }

    [ForeignKey("EmpresaId")]
    public virtual Empresas Empresa { get; set; }

    [ForeignKey("ClienteId")]
    public virtual PessoasCliente Cliente { get; set; }

    [ForeignKey("ClienteFaturamentoId")]
    public virtual PessoasCliente ClienteFaturamento { get; set; }

    [ForeignKey("PagamentoId")]
    public virtual Pagamentos Pagamento { get; set; }

    public virtual ICollection<Anexos> Anexos { get; set; }

    public virtual ICollection<ContratoItens> Items { get; set; }

    public virtual ICollection<ContasContasReceber> Contas { get; set; }
}
Lucas
  • 1,259
  • 15
  • 25
  • 1
    possibly you could have added the column after adding the table to EF, can you please remove the table from EF and Add it again – Vicky S Jun 12 '17 at 12:45
  • May be your context connection string is different than your db, can you share table script and connection string in app.config or web.config – kgzdev Jun 12 '17 at 12:48
  • @VickyS I already did this. : ( – Lucas Jun 12 '17 at 12:48
  • You need to check the Contratos table. If that column is not suppose to be there then you need to delete it from the model and re-add the table to the model. The Contratos is a child table of the Anexos model why you won't see it in the Anexox table. – Hemi81 Jun 12 '17 at 12:52
  • @IkramTurgunbaev edited – Lucas Jun 12 '17 at 12:56
  • @developer_117 `Anexos` is a dependent of `Contratos`. – Lucas Jun 12 '17 at 12:57
  • Is that 'Empresas_Id' column exists in relational table classes? – kgzdev Jun 12 '17 at 12:59
  • @IkramTurgunbaev it exists in `Contratos`, but it's `EmpresaId` and not `Empresas_Id` in that table. – Lucas Jun 12 '17 at 13:02
  • @I'mBlueDaBaDee have you checked the reference in the data model? Typically in the model if you look at the Anexox table, there might be a reference back to the Contratos table. Try deleting that reference. – Hemi81 Jun 12 '17 at 13:02
  • @I'mBlueDaBaDee In 'Contratos' table column name is 'EmpresaId', but in 'Contratos.cs' column name is 'Empresa_Id', am I right? – kgzdev Jun 12 '17 at 13:04
  • @IkramTurgunbaev in the model and in table they are the same – Lucas Jun 12 '17 at 13:07
  • @developer_117 i delete the relationship, migrated, updated, recreated, migrated, updated and... the same error ;-; – Lucas Jun 12 '17 at 13:20
  • Any chance to have something like `public ICollection Anexos { get; set; }` in your `Empresas` class? – Ivan Stoev Jun 12 '17 at 14:18
  • @IvanStoev no, not found, by the way see the answer/answer inner question. – Lucas Jun 12 '17 at 14:23
  • I saw it, but don't think it's a solution - `AsEnumerable` simply defers the execution of the query for later time, while `ToList` executes it immediately. There must be something else in the code not shown here which is causing it. Any class inheriting `Anexos`? Can you mark `Anexos` and `Empresas` as `sealed`? – Ivan Stoev Jun 12 '17 at 14:29
  • @developer_117 I answred it, any idea for the inner question? – Lucas Jun 12 '17 at 14:30
  • @IvanStoev `Anexos` doesn't inherit and no one inherit `Anexos`, yes I can mark as sealed, they are not parent of any class. – Lucas Jun 12 '17 at 14:30
  • @IkramTurgunbaev answred it, any idea for the inner question? – Lucas Jun 12 '17 at 14:41
  • @I'mBlueDaBaDee Can you show us the Contratos table as well? – Hemi81 Jun 12 '17 at 15:46
  • @developer_117 there it is. – Lucas Jun 12 '17 at 19:28
  • @developer_117 found it, see the edit – Lucas Jun 13 '17 at 13:16
  • @IkramTurgunbaev found it, see the edit – Lucas Jun 13 '17 at 13:16
  • @I'mBlueDaBaDee great :) – kgzdev Jun 13 '17 at 13:18

1 Answers1

0

So, I don't know why but, when a send to my GridView as a List<T> model it gives me that error, but if I send using AsEnumarable instead of ToList, it works:

public ActionResult IndexContratos(int id)
{
     var anexos = db.Anexos
        .Include(a => a.Contrato)
        .Include(a => a.Pessoa)
        .Include(a => a.TipoDocumento)
        .Where(x => x.ContratoId == id);

      AnexosContratoTemps(id);

      return View("Grid", anexos.AsEnumerable());//Works !!
      //return View("Grid", anexos.ToList()); //Invalid column name...
}

My View model is:

@model IEnumerable<Anexos> 

But a List<T> is a IEnumarable<T>, I really don't understand that why ToList gives me that error, can someone explain?

Edit

Finally(by coincidence) I found what was that bug, I forgot to say that the Anexos property in MyContext class was virtual, something like this:

public DbSet<Anexos> Anexos { get; set; } //WRONG!
public virtual DbSet<Anexos> Anexos { get; set; }//YAYYY!!
Lucas
  • 1,259
  • 15
  • 25