2016-04-27 61 views
1

我在我的數據庫中有兩個表,國家和州。使用代碼第一種方法,我創建了以下兩個實體:EF6不使用註釋中指定的外鍵

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; } 
} 

在狀態類,我有一個外鍵稱爲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 
+0

你試過列明關鍵的基本類型與複雜類型爲虛擬? IE公共字符串CountryCode {get; set;}然後公共虛擬Country Country {get; set;}分別在State類中? –

+0

奇怪。如果我將Country類中的[ForeignKey(「Code」)]更改爲[ForeignKey(「CountryCode」)],它將起作用。根據http://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx,這不是它的工作原理。 –

回答

0

我認爲這將解決您的問題:

  • States屬性中刪除了ForeignKey註解。
  • 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; } 
}