2017-02-13 89 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语句)时,它将连接表就像我在我的例子中那样。 –