HasPrincipalKey(),将主表外键绑定到从表的其他字段

有两个模型:

public class Customer
{
    public int Id { get; set; }
    public int Number { get; set; }
    public int ParentNumber { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string Language { get; set; }
}

public class Batch
{
    public int Id { get; set; }
    public int Number { get; set; }
    public string FileName { get; set; }
    public string ArticleNumber { get; set; }
    public string ArticleDescription { get; set; }
    public int Weight { get; set; }
    public DateTime ProductionDate { get; set; }
    public DateTime DeliveryDate { get; set; }
    public DateTime BestBeforeDate { get; set; }
    public DateTime? ApprovedDateTime { get; set; }
    public int CustomerId { get; set; }
    public virtual Customer Customer { get; set; }
}

一批可以拥有一个客户.但是,由于我们要从另一个系统导入数据,因此我们决定不接管其ID.
现在,外键显示尝试通过属性Customer.Id查找客户.

我试图实现从Batch.Customer(Id)获取外键指向Customer.Number

我将如何成功做到这一点?
我尝试通过将Customer.Number定义为具有Key属性的键..但这使主键从Id转到Number,这不是我想要的。

答案:

您要问的是在EF Core之前在EF中是不可能的.幸运的是,在EF Core中,可以使用Alternate Keys功能来完成.但是请注意,为了能够使用它,您的Cusomer.Number字段应该是唯一的.

该解决方案需要Fluent API配置.

首先将Customer.Number定义为备用键:

modelBuilder.Entity<Customer>()
    .HasAlternateKey(e => e.Number);

然后按如下所示建立关系:

modelBuilder.Entity<Batch>()
    .HasOne(e => e.Customer)
    .WithMany()
    .HasForeignKey(e => e.CustomerId)
    .HasPrincipalKey(e => e.Number);

最后两行将满足您的需求.

附带说明一下,最好为属性(和列)命名为CustomerNumber,以避免混淆其中的值.

 引用:原文链接

原文地址:https://www.cnblogs.com/Yan3399/p/15469885.html