【问题标题】:Entity Framework - Mapping Foreign Key to Business Key instead of Primary Key实体框架 - 将外键映射到业务键而不是主键
【发布时间】:2019-03-22 00:02:02
【问题描述】:

我有两个具有父/子关系的表,例如:

public class Business
    {
        public int Id { get; set; } //pk
        public int ABN { get; set; } //Business Key
        public virtual ICollection<Contract> Contracts { get; set; }
    }

public class Contract
    {
       public int Id { get; set; } //PK
       public virtual Business Business { get; set; }
       public int ABN { get; set; } //FK
    }

我想在业务键上映射从子级到父级的关系,而不是主键。我认为 FluentAPI 中的以下内容可能会解决问题,但我不知道如何映射到 BK 而不是 PK。

 modelBuilder.Entity<Contract>()
                .HasRequired(l => l.Business)
                .WithMany(f => f.Contracts)
                .HasForeignKey(l => l.ABN)

我错过了什么吗?

【问题讨论】:

    标签: .net entity-framework-6 ef-fluent-api


    【解决方案1】:

    经过进一步调查,执行此操作的方法是使用 HasPrincipalKey() 功能。例如:

     modelBuilder.Entity<Contract>()
                    .HasRequired(l => l.Business)
                    .WithMany(f => f.Contracts)
                    .HasForeignKey(l => l.ABN)
                    .HasPrincipalKey(b => b.ABN)
    

    然而,令人失望的是,这仅适用于 EntityFramework Core 而不是 EntityFramework 6.2。

    【讨论】:

    • 是的,EF Core 中引入了对备用键的支持。 EF 6 只能使用 PK 引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多