【问题标题】:EF6 Fluent API Map Related Entities On Custom Key/Properties Not PK自定义键/属性上的 EF6 Fluent API 映射相关实体不是 PK
【发布时间】:2015-10-18 13:35:18
【问题描述】:

我有以下型号

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; }
}

因此,Rate 将包含车辆,而 Vehicle 可以包含费率列表。通常我只是使用 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() 方法的另一个重载?

【问题讨论】:

  • 在我看来,在不完全了解您的域的情况下,应该使用其中一个 id。两者似乎都是 PK 级属性。也许在做映射时有一种方法可以转换为PK?
  • @MikaelEliasson 需要特殊 ID 才能将费率与车辆联系起来。 “Id”就是这样,每条记录都有一个唯一的 Id,所以我可以在需要时将其拉出并单独删除。我不明白我怎么能失去一个?我在 EF 中查找复合键,但我认为这不正确?
  • 但是车辆上的 SpecialId 是唯一的还是两辆车可以具有相同的 SpecialId?
  • @MikaelEliasson 车辆上的特殊 ID 将是唯一的。
  • 那我不明白为什么不使用正常的 1-N 关系。在速率上,它将从 ´´´SpecialId:int => VehicleId:Guid´´´ 更改并删除车辆上的 SpecialId。这映射到正常的 FK。从您的描述中我可以看到的唯一小缺点是如果您手动输入关系,因为 GUID 几乎需要复制和粘贴。

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


【解决方案1】:

我认为 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);

【讨论】:

  • 我认为这是正确的。但是对于查询,您实际上并不需要映射关系。无论如何,您都可以使用连接查询它。如果您需要外键约束,您可以在迁移或类似操作中手动添加。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多