简体   繁体   中英

C# code-first EF 6. Invalid Column Name

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

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!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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