2

在EF5中,使用代码优先的方法和流畅的API,如何基于不是另一个表的主键的键来创建导航属性(多对1)?如何使用不是第二个对象的主键的键创建导航属性?

我的数据库模型是这样的,而且我不能改变它

  • TableFoo1
    • Foo1ID INT(键)
    • 字段1 INT
    • 值VARCHAR
  • TableFoo2
    • Foo2ID INT(键)
    • 字段1 INT
    • 值VARCHAR
  • TableBar
    • BarID INT(键)
    • 字段1 INT
    • 值VARCHAR

我希望我的这些实体:

public class Foo1 
{ 
    public int Foo1ID { get; set; } 
    public int BarID { get; set; } //It corresponds Bar.ID 
    public string Value { get; set; } 
    public Bar Bar { get; set; } 
} 

public class Foo2 
{ 
    public int Foo2ID { get; set; } 
    public int BarID { get; set; } //It corresponds to Bar.Field1, NOT Bar.ID 
    public string Value { get; set; } 
    public Bar Bar { get; set; } 
} 

public class Bar 
{ 
    public int ID { get; set; } 
    public int Field1 { get; set; } 
    public string Value { get; set; } 
} 

这里是我的地图(:第二个是不完整的一个):

public class Foo1Map : EntityTypeConfiguration<Foo1> 
{ 
    public Foo1Map() 
    { 
     this.HasKey(e => e.Foo1ID); 

     // Links to Bar's Primary Key, yay, it's easy. 
     this.HasRequired(e => e.Bar).WithMany().HasForeignKey(e => e.BarID); 
    } 
} 

public class Foo2Map : EntityTypeConfiguration<Foo2> 
{ 
    public Foo2Map() 
    { 
     this.HasKey(e => e.Foo2ID); 

     // No clues of how to links to Bar's other unique column, but not primary key. 
     this.HasRequired(e => e.Bar).WithMany()........? 
    } 
} 

public class BarMap : EntityTypeConfiguration<Bar> 
{ 
    public BarMap() 
    { 
     this.HasKey(e => e.BarID); 
    } 
} 
+1

可能重复[在主表中创建与重命名字段和非主键的实体关系](http://stackoverflow.com/questions/15352114/creating-entity-relationship-with-renamed-fields-and-non -primary-key-in-primary) – Slauma 2013-03-25 18:32:57

+0

我看到另一篇文章说了同样的事情,但年龄较大,所以我不知道它是EF5还是EF1。你链接的一个清楚地表明它仍然是最新的EF5(并将为EF6)。谢谢,我会结束我的问题。 – Tipx 2013-03-25 18:45:13

+0

另外,我添加了一个解决此问题的解决方案,可以在某些情况下使用。 – Tipx 2013-03-25 18:51:51

回答

0

我问的问题,其中Foo1Foo2的情况下,这两个链接到Bar与不同的密钥(在Bar方)不能在EF5中完成(更详细的信息在这个问题是几乎重复的)原样。但是,如果您的所有对象(这里的Foo1Foo2)都需要映射到相同的列(具有唯一性约束),即使它不是其他对象的PK(此处为Bar),您可以设置该列成为关键。此外,如果您不想使用同一列Foo1Foo2,但在上下文的同一实例中,您永远不需要使用Foo1Foo2,但可以使用动态映射,但它很危险并且有很多复杂性。

相关问题