EF6不使用注释中指定的外键

时间:2016-04-27 20:29:58

标签: c# entity-framework

我的数据库,国家和州都有两张表。使用Code第一种方法,我创建了以下两个实体:

public partial class Country
{
    [Key]
    [Column(Order = 1)] 
    [Required]
    [StringLength(3)]
    public string Code { get; set; }  //Country Code

    [Required]
    [StringLength(50)]
    public string Description { get; set; }  // Country Description

    [ForeignKey("Code")]
    public IList<State> States { get; set; }

}

public partial class State
{
    [Key]
    [Column(Order = 1)] 
    [Required]
    [StringLength(3)]
    public string CountryCode { get; set; }  //Country Code

    [Key]
    [Column(Order = 2)]
    [Required]
    [StringLength(3)]
    public string Code { get; set; }  //State Code

    [Required]
    [StringLength(60)]
    public string Description { get; set; }  //State Description

    [ForeignKey("CountryCode")]
    public Country Country { get; set; }
}

在State类中,我有一个名为CountryCode的外键,这是我期望EF用来连接这两个实体的。但事实并非如此。相反,它正在使用State类中的Code字段加入Country类中的Code字段。我在这做错了什么。下面是它生成的sql:

SELECT 
[Project2].[C1] AS [C1], 
[Project2].[Code] AS [Code], 
[Project2].[Description] AS [Description], 
[Project2].[C2] AS [C2], 
[Project2].[CountryCode] AS [CountryCode], 
[Project2].[Code1] AS [Code1], 
[Project2].[Description1] AS [Description1]
FROM ( SELECT 
    [Limit1].[Code] AS [Code], 
    [Limit1].[Description] AS [Description], 
    [Limit1].[C1] AS [C1], 
    [Extent2].[CountryCode] AS [CountryCode], 
    [Extent2].[Code] AS [Code1], 
    [Extent2].[Description] AS [Description1], 
    CASE WHEN ([Extent2].[CountryCode] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2]
    FROM   (SELECT TOP (1) 
        [Extent1].[Code] AS [Code], 
        [Extent1].[Description] AS [Description], 
        1 AS [C1]
        FROM [dbo].[Countries] AS [Extent1]
        WHERE [Extent1].[Code] = @p__linq__0 ) AS [Limit1]
    LEFT OUTER JOIN [dbo].[States] AS [Extent2] ON [Limit1].[Code] = [Extent2].[Code]
)  AS [Project2]
ORDER BY [Project2].[Code] ASC, [Project2].[C2] ASC

1 个答案:

答案 0 :(得分:0)

我认为这可以解决您的问题:

  • ForeignKey属性中删除States注释。
  • InverseProperty媒体资源添加Country注释。

<强> BEFORE:

public partial class Country
{
    /* other properties */

    [ForeignKey("Code")]
    public IList<State> States { get; set; }
}

public partial class State
{
    /* other properties */

    [ForeignKey("CountryCode")]
    public Country Country { get; set; }
}

<强> AFTER:

public partial class Country
{
    /* other properties */

    public IList<State> States { get; set; }
}

public partial class State
{
    /* other properties */

    [ForeignKey("CountryCode")]
    [InverseProperty("States")]
    public Country Country { get; set; }
}