Jeff Hornby
Jeff Hornby

Reputation: 13640

Entity Framework 7 Invalid Column Name

I'm creating EF7 mappings for an existing database and I'm getting an "Invalid column name" error. The code that is throwing the error is:

public class DepositContext : DbContext
{
    public DbSet<tblBatch> Batches { get; set; }
    public DbSet<tblTransaction> Transactions { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<tblBatch>().HasKey(b => b.BatchID);

        modelBuilder.Entity<tblTransaction>().HasKey(t => t.TransactionID);

        modelBuilder.Entity<tblBatch>().HasMany(b => b.tblTransactions).WithOne().HasForeignKey(t => t.fBatchID);
    }
}

public class tblBatch
{
    public int BatchID { get; set; }
    public int? fDepositID { get; set; }
    public Guid BRN { get; set; }
    public string BCN { get; set; }
    public decimal? BCT { get; set; }
    public string BatchFileName { get; set; }

    public List<tblTransaction> tblTransactions { get; set; }
}

public class tblTransaction
{
    public int TransactionID { get; set; }
    public string TRN { get; set; }
    public string TransactionStatus { get; set; }

    public int fBatchID { get; set; }
    public tblBatch tblBatch { get; set; }
}

This is throwing a Invalid column name 'tblBatchBatchID1'. And when I use SQL Profiler to see what is being sent to the database, it is:

exec sp_executesql N'SELECT [t].[TransactionID], [t].[fBatchID], [t].[TRN], [t].[TransactionStatus], [t].[tblBatchBatchID1]
FROM [tblTransaction] AS [t]
INNER JOIN (
    SELECT DISTINCT TOP(1) [b].[BatchID]
    FROM [tblBatch] AS [b]
    WHERE [b].[BatchID] = @__BatchId_0
) AS [b] ON [t].[fBatchID] = [b].[BatchID]
ORDER BY [b].[BatchID]',N'@__BatchId_0 int',@__BatchId_0=37

Does anybody know how to fix this?

Upvotes: 1

Views: 1767

Answers (1)

natemcmaster
natemcmaster

Reputation: 26763

There were some bugs in EF RC1 that produced the wrong column name in query generation. See this list of bugs that might be related to your issue.

You can attempt to work around this by explicitly setting the column name.

modelBuilder.Entity<tblBatch>().Property(e => e.BatchID).HasColumnName("BatchID");

If you're feeling brave, you can try upgrading to RC2 nightlies of EF Core and see if the issue is fixed there.

Upvotes: 2

Related Questions