AspNet EF将外键引用到字段 [英] AspNet EF referencing foreign key to field

查看:218
本文介绍了AspNet EF将外键引用到字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:

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's. 现在,外键显示尝试通过属性Customer.Id

One batch can have a customer attached to it. But since we're importing the data from another system we decided not to take over their id's. Right now the foreign key says try to find a customer by the property Customer.Id

我正在尝试实现将外键从Batch.Customer(Id)指向Customer.Number

I'm trying to achieve to get the foreign key point to Customer.Number from Batch.Customer(Id)

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

How would i succeed in this? I've tried by defining the Customer.Number to be a Key with the Key attribute.. but this made the primary key go from Id to Number which is not what i wanted...

推荐答案

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

What are you asking was impossible in EF prior to EF Core. Fortunately in EF Core it can be done by using Alternate Keys feature. But please note that in order to be able to use it, your Cusomer.Number field should be unique.

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

The solution requires Fluent API configuration.

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

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

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

Then set up the relationship as follows:

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

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

The last two lines will do what you are seeking for.

请注意,最好将属性(和列)命名为CustomerNumber,以避免混淆其中的值.

As a side note, it would be better to name the property (and column) CustomerNumber in order to avoid confusion of what the value is in it.

这篇关于AspNet EF将外键引用到字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆