实体框架 - 将外键映射到业务密钥而不是主键

问题描述 投票:0回答:1

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

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个回答
0
投票

经过进一步调查,执行此操作的方法是使用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。

© www.soinside.com 2019 - 2024. All rights reserved.