我正在構建一個連接到舊數據庫(無法修改)的EF4的新服務。實體框架4與非鍵列/字段和不同列/字段名稱的關聯
(這BD似乎已經由DB天才,你會看到的骯髒的工作,我知道建的,但我必須這樣做)
基本上,我有兩個表(SegurosPassageiros和LocsPassageiros),其鍵與常規方式與其他表相關聯。如以下模型所示,它們與PK/FK沒有物理關聯,但它們通過非鍵列「SegurosPassageiros.CodPassageiro」和「LocsPassageiros.CodLocPassageiroInterno」鏈接。 此外,該協會是一個一對多:
LocsPassageiros 1 ... * SegurosPassageiros
我發現與非重點的關聯很多答案,但不能同時非鍵和不同的名稱在同一場景中。
的表:
LocsPassageiros
----------------------------------
CodLocPassageiro (PK) | int
Nome | varchar
CodLocPassageiroInterno | int
----------------------------------
----------------------------------
SegurosPassageiros
----------------------------------
CodSeguroPassageiro(PK) | int
CodPassageiro | int
----------------------------------
代碼(類 「SeguroPassageiro」 映射到表 「SegurosPassageiros」):
public class SeguroPassageiro
{
[Key]
public Int32 CodSeguroPassageiro { get; set; }
.... (other fields)
//tried this, no success
//[ForeignKey("Passageiro")]
public virtual Int32 CodLocPassageiroInterno { get; set; }
//tried this annotation with no success
[Association("Passageiro_Seguros", "CodPassageiro", "CodLocPassageiroInterno")]
public virtual Passageiro Passageiro { get; set; }
}
類 「Passageiro」 映射到表 「LocsPassageiros」:
public class Passageiro
{
[Key]
public Int32 CodLocPassageiro { get; set; }
... (other fields)
//tried this, no success
//[ForeignKey("Seguros")]
public Int32 CodLocPassageiroInterno { get; set; }
//tried these annotations with no success
[ForeignKey("CodLocPassageiroInterno")]
[Association("Passageiro_Seguros", "CodLocPassageiroInterno", "CodPassageiro")]
public List<SeguroPassageiro> Seguros { get; set; }
}
設置型號:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Dominio.Aereo.Passageiro>().ToTable("LocsPassageiros");
modelBuilder.Entity<Dominio.Aereo.SeguroPassageiro>()
.ToTable("SegurosPassageiros");
//Tried both lines below (together and separeted) with no success:
//modelBuilder.Entity<Dominio.Aereo.SeguroPassageiro>().HasRequired(s => s.Passageiro).WithOptional();
//modelBuilder.Entity<Dominio.Aereo.Passageiro>().HasMany(p => p.Seguros).WithRequired();
//Tried "linking" the column "CodPassageiro" on table "SegurosPassageiros" to
//column "CodLocPassageiroInterno" on table "LocsPassageiros". No success.
modelBuilder.Entity<Dominio.Aereo.SeguroPassageiro>().Property(s => s.CodLocPassageiroInterno).HasColumnName("CodPassageiro");
}
在這種模式下,幾十個試驗,我能到達漸漸在Passageiro對象,但與錯誤相關聯的列表中最接近後: 「SegurosPassageiros.CodPassageiro」和「LocsPassageiros.CodLocPassageiro」(而不是「LocsPassageiros .CodLocPassageiro * Interno *「)。 EF堅持要得到錯誤的關聯(在LocsPassageiros上獲得PK)。
任何人都知道我怎麼能在EF中獲得這個關聯?
你是對的。我已經實現了這種方式。像魅力一樣工作,唯一的缺點是現在我有很多選擇(根據記錄數量大約3或4)。 乾杯隊友! – 2012-08-07 21:39:41
很高興爲你工作..我有特權發表評論..感謝您接受此爲答案.. :) – sak 2012-08-08 04:58:27