我正在使用EF4构建一个新服务,该服务连接到遗留数据库(无法修改)。
(这个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对象中获得一个List,但关联错误: “SegurosPassageiros.CodPassageiro”和“LocsPassageiros.CodLocPassageiro”(而不是“LocsPassageiros.CodLocPassageiro * Interno * ”)。 EF坚持要获得错误的关联(在LocsPassageiros上获得PK)。
任何人都知道如何在EF中获得这种关联?
答案 0 :(得分:3)
不幸的是,这是不可能的。 EF只能在主体实体中定义的PK之上构建一对多关系。在您的情况下,仅当LocsPassageiros.CodLocPassageiro
用作主键时。
在数据库中,只有在主键是唯一的时才能构建这种关系 - 它必须是主键或必须具有唯一约束。如果数据库不满足这些要求,则该关系无效。 EF目前不支持唯一约束,因此唯一的方法是使用主键。
答案 1 :(得分:2)
这是一个解决方法。 (如果我有权将此作为评论发布,我不会将此作为答案发布。) 您可以使用EF查询并加入Where中的实体,而不是直接使用Association。