EntityFramework 6使用错误的列作为父ID

时间:2015-11-21 23:40:31

标签: c# entity-framework foreign-keys entity-framework-6

我正在使用一些代码,其中记录在Entity Framework 6中有子记录。

然而,我遇到的问题是,当EF生成SQL来选择子记录时,它正在选择子模型中的错误列来关闭。

示例代码(为简洁而剪裁了一些属性):

[Table("OrderTracking")]
public class OrderTrackingEntity
{
    [Key]
    public int          ID                  { get; set; }

    public int?         OrderEntryID        { get; set; }
    public string       PONumber            { get; set; }
    public string       OrderType           { get; set; }
    public int?         CustomerID          { get; set; }
    public int?         ManufacturerID      { get; set; }

    public string       Name                { get; set; }
    public string       Address1            { get; set; }

    public virtual ICollection<OrderTrackingDetailEntity> Items { get; set; }
}

[Table("OrderTrackingDetails")]
public class OrderTrackingDetailEntity
{
    // I want to key off of this field, OrderTrackingID == OrderTrackingEntity.ID
    [Key, Column(Order = 0)]
    public int          OrderTrackingID         { get; set; }

    // EF Keeps on selecting this field
    [Key, Column(Order = 1)]
    public int          ID                      { get; set; }

    public string       LineNumber              { get; set; }
    public decimal?     UnitPrice               { get; set; }
    public int          Quantity                { get; set; }
}

输出SQL如下:

SELECT 
    [Extent1].[OrderTrackingID] AS [OrderTrackingID], 
    [Extent1].[ID] AS [ID], 
    [Extent1].[LineNumber] AS [LineNumber], 
    [Extent1].[UnitPrice] AS [UnitPrice], 
    [Extent1].[Quantity] AS [Quantity], 
    FROM [dbo].[OrderTrackingDetails] AS [Extent1]
    WHERE [Extent1].[ID] = @EntityKeyValue1 -- << WRONG FIELD

如何使用OrderTrackingDetailEntity.OrderTrackingID作为关键字ID? (最好使用属性)

2 个答案:

答案 0 :(得分:2)

首先,您的子实体没有导航属性。现在EF应该选择合适的房产。但是,我更喜欢明确这些内容,所以我也会添加ForeignKey属性:

[ForeignKey("OrderTrackingID")]
public virtual OrderTrackingEntity OrderTracking { get; set; }

答案 1 :(得分:1)

您可以像这样在DbContext中进行配置,但它还要求您从OrderTrackingID属性中删除[Key] attrobute:

modelBuilder.Entity<OrderTrackingEntity>().HasMany(x => x.OrderTrackingDetailEntity).WithRequired().HasForeignKey(x=>x.OrderTrackingID         );

因为在我看来,您的OrderTrackingID属性不是真正的密钥,而是外键。

还要考虑引用真实实体,而不是只保留关系的关键字。

您可以更新OrderTrackingDetailEntity以引用OrderTrackingEntity而不是只有一个键,它可以正常映射:

[Table("OrderTrackingDetails")]
public class OrderTrackingDetailEntity
{
    public int          OrderTrackingID         { get; set; }
    [ForeignKey("OrderTrackingID")]
    public OrderTrackingEntity OrderTracking         { get; set; }

    // EF Keeps on selecting this field
    [Key, Column(Order = 1)]
    public int          ID                      { get; set; }

    public string       LineNumber              { get; set; }
    public decimal?     UnitPrice               { get; set; }
    public int          Quantity                { get; set; }
}