实体框架7无效的列名称

时间:2016-04-04 21:45:15

标签: c# entity-framework entity-framework-core

我正在为现有数据库创建EF7映射,并且我收到“无效列名”错误。抛出错误的代码是:

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

这会引发Invalid column name 'tblBatchBatchID1'.当我使用SQL事件探查器查看发送到数据库的内容时,它是:

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

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

EF RC1中存在一些错误,这些错误在查询生成中产生了错误的列名。请参阅可能与您的问题相关的this list of bugs

您可以尝试通过显式设置列名来解决此问题。

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

如果您有勇气,可以尝试升级到RC Core的RC2夜魇,看看问题是否已解决。