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);
}
}
可能重复[在主表中创建与重命名字段和非主键的实体关系](http://stackoverflow.com/questions/15352114/creating-entity-relationship-with-renamed-fields-and-non -primary-key-in-primary) – Slauma 2013-03-25 18:32:57
我看到另一篇文章说了同样的事情,但年龄较大,所以我不知道它是EF5还是EF1。你链接的一个清楚地表明它仍然是最新的EF5(并将为EF6)。谢谢,我会结束我的问题。 – Tipx 2013-03-25 18:45:13
另外,我添加了一个解决此问题的解决方案,可以在某些情况下使用。 – Tipx 2013-03-25 18:51:51