简体   繁体   English

EFCore 在 select 中生成幻像列名

[英]EFCore generates phantom column name in select

I am upgrading a project to EFCore 2.2.0 from 2.1.3 and encountered this bizarre issue.我正在将一个项目从 2.1.3 升级到 EFCore 2.2.0 并遇到了这个奇怪的问题。 When loading data for a simple table, I get an exception that 'ExchangeCd1' is not defined.为简单表加载数据时,出现未定义“ExchangeCd1”的异常。 This column does not exist, but it is not referenced anywhere in the code.此列不存在,但未在代码中的任何位置引用。 When I examine the mapping properties, I see it is listed as: {Property: ExchangeHoliday.ExchangeCd1 (no field, string) Shadow FK Index 2 2 2 0 1}当我检查映射属性时,我看到它被列为:{Property: ExchangeHoliday.ExchangeCd1 (no field, string) Shadow FK Index 2 2 2 0 1}

The classes are pretty simple, but the child has a composite primary key and the parent tries to reference it using its individual key.这些类非常简单,但是子级有一个复合主键,父级尝试使用其单独的键来引用它。

public class Exchange
{
    public string ExchangeCd { get; set; }

    public string ExchangeName { get; set; }

    public DayOfWeek WeekendStart { get; set; }

    public DayOfWeek WeekendEnd { get; set; }

    public ICollection<ExchangeHoliday> Holidays { get; set; }
}

public class ExchangeHoliday
{
    public string ExchangeCd { get; set; }

    public DateTime HolidayDate { get; set; }

    public bool IsTradeHoliday { get; set; }

    public bool IsSettleHoliday { get; set; }
}

I add some mapping, in order to define the primary key as a composite key我添加了一些映射,以便将主键定义为复合键

modelBuilder.Entity<Exchange>().HasKey(e => e.ExchangeCd);
modelBuilder.Entity<ExchangeHoliday>().HasKey(e => new { e.ExchangeCd, e.HolidayDate });

Then I execute a very simple select然后我执行一个非常简单的选择

var holidays = await dbContext.ExchangeHolidays.ToArrayAsync(cancellationToken).ConfigureAwait(false);

I turned on EFCore SQL logging, and it generates this for the SQL我打开了 EFCore SQL 日志记录,它为 SQL 生成了这个

SELECT [e].[exchange_cd], [e].[holiday_date], [e].[ExchangeCd1], [e].[is_settle_holiday], [e].[is_trade_holiday]
FROM [exchange_holiday] AS [e]

I tried to add explicit mapping to remove the shadow key, but it sticks around我尝试添加显式映射以删除阴影键,但它仍然存在

modelBuilder.Entity<Exchange>()
                    .HasMany<ExchangeHoliday>()
                    .WithOne(e => e.Exchange)
                    .HasForeignKey(fk => fk.ExchangeCd);

Ok, so if I do the mapping on the child, it resolves the issue好的,所以如果我对孩子进行映射,它就解决了问题

modelBuilder.Entity<ExchangeHoliday>()
                    .HasOne<Exchange>()
                    .WithMany(e => e.Holidays)
                    .HasForeignKey(e => e.ExchangeCd);

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

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