我的EF6(代码优先)应用程序中有以下代码行:
var priceDetail = context.PriceLists.Include(pl => pl.PriceDetails).FirstOrDefault();
我的目标是检索第一个PriceList
对象,其中包含PriceDetail
s的集合。
当该行执行时,我收到此错误:
-- Failed in 12 ms with error: Invalid column name 'Order_OrderNumber'.
这对我来说很奇怪,因为PriceList
和PriceDetail
对象都没有引用Order
对象。这是PriceList对象:
[Table( "dbo.PriceList" )]
public class PriceList
{
public int PriceListId { get; set; }
[StringLength( 150 )]
[Display( Name = "PriceList name" )]
public string PriceListDesc { get; set; }
public virtual ICollection<PriceListDetail> PriceDetails { get; set; }
}
这是PriceDetail对象:
[Table( "dbo.PriceDetail" )]
public class PriceDetail
{
[ColumnDesc( "Primary key" )]
public int PriceDetailId { get; set; }
[ForeignKey( "PriceList" )]
public int PriceListId { get; set; }
public PriceList PriceList { get; set; }
[ForeignKey( "Item" )]
public int ItemNumber { get; set; }
public Item Item { get; set; }
public Decimal Price { get; set; }
public Decimal? CostMultiplier { get; set; }
}
EF生成的完整SQL查询如下:
SELECT
[Project1].[PriceListId] AS [PriceListId],
[Project1].[PriceListDesc] AS [PriceListDesc],
[Project1].[C1] AS [C1],
[Project1].[PriceDetailId] AS [PriceDetailId],
[Project1].[PriceListId1] AS [PriceListId1],
[Project1].[ItemNumber] AS [ItemNumber],
[Project1].[PriceList] AS [PriceList],
[Project1].[Order_OrderNumber] AS [Order_OrderNumber]
FROM ( SELECT
[Limit1].[PriceListId] AS [PriceListId],
[Limit1].[PriceListDesc] AS [PriceListDesc],
[Extent2].[PriceDetailId] AS [PriceDetailId],
[Extent2].[PriceListId] AS [PriceListId1],
[Extent2].[ItemNumber] AS [ItemNumber],
[Extent2].[PriceList] AS [PriceList],
[Extent2].[Order_OrderNumber] AS [Order_OrderNumber],
CASE WHEN ([Extent2].[PriceDetailId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
FROM (SELECT TOP (1) [c].[PriceListId] AS [PriceListId], [c].[PriceListDesc] AS [PriceListDesc]
FROM [Admin].[PriceList] AS [c] ) AS [Limit1]
LEFT OUTER JOIN [Admin].[PriceDetail] AS [Extent2] ON [Limit1].[PriceListId] = [Extent2].[PriceListId]
) AS [Project1]
ORDER BY [Project1].[PriceListId] ASC, [Project1].[C1] ASC
为什么我收到此错误?
答案 0 :(得分:1)
我终于弄明白了。在我的Order
对象中,我有以下代码行:
public ICollection<PriceDetail> PriceDetails => AssignedLocation?.LocationDetail?.PriceList?.PriceDetails;
为方便起见,这纯粹是一个访问器,因此订单对象可以更容易地到达子子类。
由于某种原因,我不完全理解,实体框架将此解释为表示PriceDetail
和Order
表之间存在某种关系,导致上述查询。
决议很简单:
[NotMapped]
public ICollection<PriceDetail> PriceDetails => AssignedLocation?.LocationDetail?.PriceList?.PriceDetails;
添加此属性足以解除实体框架的混淆。