2012-07-12 114 views
0

我正在使用現有數據庫,因此更改模式不是一個選項。以下是我正在使用的表格...使用實體框架與兩個外鍵定義的一對多關係

Product 
------------------------------------- 
ID    - GUID   [PK] 
Name    - varchar(100) 
ModelId   - GUID   [FK1, FK2] 
SoftWareVersion - varchar(10) [FK2] 

[FK1] Foreign Key to Model table 
[FK2] Foreign Composite key to SoftwareVersion table 


ProductModel 
------------------------------------- 
ID    - GUID   [PK] 
ModelName  - varchar(100) 


SoftwareVersion 
------------------------------------- 
ID    - GUID   [PK] 
Version   - varchar(10) 
ModelId   - GUID   [FK1] 

[FK1] Foreign Key to Model table 

每個單獨產品都安裝有軟件。我們有幾種產品模型,每種產品都明顯與單一模型(產品[FK1])相關聯。

在每個產品型號的生命週期中,它可能有多個軟件更新/版本。同樣,該軟件可能安裝在許多型號上。

我需要能夠採取的ProductID並返回安裝在該特定產品的軟件版本。通常我會得到與我正在查找的產品型號相關的軟件版本,但型號可能有幾個更新。我無法單獨查找Product.SoftwareVersion字段,因爲它會返回安裝了該軟件的所有不同模型。

所以,最後我需要在ModelId &版本匹配的產品,我望着從SoftwareVersion返回的記錄。

我想返回SoftwareVersion作爲產品的屬性...

Product.SoftwareVersion 

在我ProductEntity的定義,我有以下...

[Table("Product")] 
public class ProductEntity 
{ 
    [ForeignKey("Model")] 
    public Guid ModelID { get; set; } 
    public virtual ProductModelEntity Model { get; set; } 


    [ForeignKey("SoftwareVersion")] 
    public String SoftwareVersionNumber { get; set; } 
    public virtual SoftwareVersionEntity SoftwareVersion { get; set; } 
} 

所以 「ModelID」爲模型執行外鍵的角色,並作爲SoftwareVersion的組合外鍵的一部分。我卻無法分配多個ForeignKey的屬性相同的屬性...

[ForeignKey("Model"),ForeignKey("SoftwareVersion")] 
public Guid ModelID { get; set; } 
public virtual ProductModelEntity Model { get; set; } 

我更願意與更多鈔票,如果屬性的工作,但我開到其他技術也是如此。 (屬性直接在相關代碼中描述類,而不是在圖書館週圍擴展定義,很好理解你在看什麼,而不是花時間去追求定義......但我離題了!)

任何幫助一如既往是不勝感激。

謝謝

-G

回答

0

我認爲下面的註釋都將工作:

[Table("Product")] 
public class ProductEntity 
{ 
    public Guid ModelID { get; set; } 
    public String SoftwareVersionNumber { get; set; } 

    [ForeignKey("ModelID, SoftwareVersionNumber")] 
    public virtual ProductModelEntity Model { get; set; } 

    [ForeignKey("SoftwareVersionNumber")] 
    public virtual SoftwareVersionEntity SoftwareVersion { get; set; } 
} 

或者:

[Table("Product")] 
public class ProductEntity 
{ 
    [ForeignKey("Model"), Column(Order = 1)] 
    public Guid ModelID { get; set; } 

    [ForeignKey("Model"), ForeignKey("SoftwareVersion"), Column(Order = 2)] 
    public String SoftwareVersionNumber { get; set; } 

    public virtual ProductModelEntity Model { get; set; } 
    public virtual SoftwareVersionEntity SoftwareVersion { get; set; } 
}