2017-02-13 94 views
0

由於我的數據庫設置(我沒有控制權)的方式,我有一個外鍵的情況,我無法弄清楚在實體框架。我正在使用Fluent API來配置我的關係。我的班是非標準的非唯一外鍵

public class Parent 
{ 
    // Unique primary key 
    public int PrimaryKey { get; set; } 

    // These two fields together compose the foreign key to join to Child 
    public string ParentForeignKey1 { get; set; } 
    public string ParentForeignKey2 { get; set; } 

    public List<Child> Children { get; set; } 
} 

public class Child 
{ 
    // Unique primary key 
    public int PrimaryKey { get; set; } 

    // These two fields together compose the (non-unique) foreign key to join to Parent 
    public string ChildForeignKey1 { get; set; } 
    public string ChildForeignKey2 { get; set; } 

    // The parent/child relationship is implicit, even though the tables 
    // themselves indicate a many-to-many relationship 
    public List<Parent> Parents { get; set; } 
} 

實體框架的關係應該是這樣的,兩個表上ParentForeignKeyChildForeignKey領域加入像

SELECT * 
FROM Parent 
JOIN Child 
ON Child.ChildForeignKey1 = Parent.ParentForeignKey1 
AND Child.ChildForeignKey2 = Parent.ParentForeignKey2 

如何建立良好的API外鍵映射,使實體當我查詢DbSet時,框架會生成這些連接?

+0

你只有一個家長。你不應該在代碼中有一個名單? – jdweng

+0

好點。我會更新這個問題。我沒有這樣做,因爲父/子關係是隱含的(即使SQL連接實際上是多對多,每個子節點只有一個父節點)。 –

回答

0

我想這更有意義

public class Parent 
{ 
    // The parent/child relationship is implicit, even though the tables 
    // themselves indicate a many-to-many relationship 
    public static List<Parent> Parents { get; set; } 


    // Unique primary key 
    public int PrimaryKey { get; set; } 

    // These two fields together compose the foreign key to join to Child 
    public string ParentForeignKey1 { get; set; } 
    public string ParentForeignKey2 { get; set; } 

    public List<Child> Children { get; set; } 
} 

public class Child 
{ 
    // Unique primary key 
    public int PrimaryKey { get; set; } 

    // These two fields together compose the (non-unique) foreign key to join to Parent 
    public string ChildForeignKey1 { get; set; } 
    public string ChildForeignKey2 { get; set; } 

} 
+0

什麼把靜態屬性放在'Parent'中呢? –

+0

爲父類的每個實例創建一個共同的List <>對象。這兩個班代表你最終的結果。兒童課程輸入來自哪裏? Parent類中的Children是一個鏈接,但是您沒有輸入Child的List <>。我認爲你還需要一個靜態的兒童列表<> – jdweng

+0

也許我在我的原始問題不清楚。我想知道如何設置外鍵關係('... HasForeignKey()...'),以便實體框架生成SQL以將「Parent」連接到「Child」(來自LINQ語句)時,它將連接表就像我在我的例子中那樣。 –