自定义键/属性上的EF6 Fluent API Map相关实体不是PK

时间:2015-10-18 13:35:18

标签: c# entity-framework entity-framework-6 ef-fluent-api

我有以下型号

public class Rate
{
    public Guid Id { get; set; } // PK
    public int SpecialId { get; set; }

    [Column(TypeName = "Money")]
    public decimal Rental { get; set; }
    public virtual Vehicle Vehicle { get; set; }
}

以下......

public class Vehicle
{
    public Guid Id { get; set; } // PK
    public int SpecialId { get; set; }

    public string Manufacturer { get; set; }
    public string Model { get; set; }

    // List of rates on
    public virtual ICollection<Rate> Rates { get; set; }
}

因此,费率可以有车辆,车辆可以有费率列表。通常情况下,我只是使用PK进行映射,EF效果很好。

然而,在这种情况下,我需要使用SpecialId映射/加入它们。我在Rate Mapping类中开始使用以下内容,但只能映射连接的一侧。我怎么告诉它不要使用PK id而是使用SpecialId用于双方?

 HasKey(x => x.Id);
 Property(x => x.Id).IsRequired();
 Property(x => x.SpecialId).IsRequired();
 HasOptional(x => x.Vehicle).WithMany(x => x.Rates).Map(m => m.MapKey("SpecialId"));

有没有办法在Rate和Vehicle表上使用SpecialId来加入这两者。也许是.Map()方法的另一个重载?

1 个答案:

答案 0 :(得分:2)

我认为EF 6.x及之前版本不支持您所需的内容,但在EF 7中,它被称为 Alternate Key 。在你的情况下,它将是:

Entity<Rate>().Reference(r=>r.Vehicle)
              .InverseCollection(v=>v.Rates)
              .ForeignKey(r=>r.SpecialId)
              .PrincipalForeignKey(v=>v.SpecialId);
相关问题