在 EF5 中,使用代码优先方法和流畅的 API,如何根据不是其他表的主键的键创建导航属性(多对 1)?
我的数据库模型就是这样,我无法更改它:
- 表Foo1
- Foo1ID 整数(键)
- 字段 1 整数
- 值 varchar
- 表Foo2
- Foo2ID 整数(键)
- 字段 1 整数
- 值 varchar
- 表格栏
- BarID int(键)
- 字段 1 整数
- 值 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);
}
}