我在MVC 5.2,EF 6.1.3和SQL Server 2008 R2中使用代码优先。
有两个表:项目和显示。 Item有一个名为PreOrderDisplayID的列,其中包含Display.DisplayID的外键。
在EF图层中,我有:
class Item
public int? PreOrderDisplayID { get; set; }
public virtual Display PreOrderDisplay { get; set; }
...
class Display
public int DisplayID { get; set; }
public virtual ICollection<Item> PreOrderItems { get; set; }
...
class OrdersContext : DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Display>()
.HasMany(e => e.PreOrderItems)
.WithOptional(e => e.PreOrderDisplay)
.HasForeignKey(e => e.PreOrderDisplayID);
}
...
当我尝试通过EF查询此表时,我得到:
列名称无效&#39; Display_DisplayID&#39;。
并且,我可以看到,EF正在使用不存在的列生成SQL:
INNER JOIN [dbo].[Item] AS [Extent2] ON [Extent1].[ItemID] = [Extent2].[ItemID]
...
LEFT OUTER JOIN [dbo].[Display] AS [Extent5] ON [Extent2].[Display_DisplayID] = [Extent5].[DisplayID]
我做错了什么?谢谢。
答案 0 :(得分:0)
The issue was that before I added PreOrderDisplay and PreOrderDisplayID to Item, there was already another relation in Item to Display via the Item.Display and Item.DisplayID properties. That relation was working fine without the HasForeignKey clause before, but once the new relation was added, I had to go to the original relation and add the HasForeignKey clause:
modelBuilder.Entity<Display>()
.HasMany(e => e.Items)
.WithOptional(e => e.Display)
.HasForeignKey(e => e.DisplayID);