【问题标题】:Is it possible to create a Domain Class which has Multiple FK Columns to same PK?是否可以创建一个具有多个 FK 列到同一个 PK 的域类?
【发布时间】:2018-09-01 11:34:46
【问题描述】:

我是设计数据库的新手。

我有问题如何定义一个域类,它有多个外键链接到同一个主键。

这是我的模型:

namespace OceanFmsSystem.Domain
{
    public class ExportTemplate
    {
        public int Id { get; set; }
        public List<ExportBooking> ExportBookings { get; set; }
        public string TemplateName { get; set; }
        public int CustomerId { get; set; }
        public string Incoterms { get; set; } 
        public string IncotermsDetail { get; set; }
        public string PaymentTerm{ get; set; }
        public int CountryOriginId { get; set; }
        public int CountryDestinationId { get; set; }
    }
}

我想要做的是CountryOriginId & CountryDestinationId 应该将下面的类称为外键:

namespace OceanFmsSystem.Domain
{
    public class Country
    {
        public int Id { get; set; }
        public string CountryCode { get; set; }
        public string CountryName { get; set; }
    }
}

据我所知,在 EF Core 中有一个约定,我应该将外键命名如下,以便从代码迁移到数据库。

public type ClassNameOfPrimaryKeyId { get; set;}

有没有什么办法可以做到这一点?

【问题讨论】:

    标签: sql entity-framework database-design


    【解决方案1】:

    是的,可能。你的类应该是这样的:

    public class ExportTemplate
    {
        //...
    
        public int CountryOriginId { get; set; }
        public Country CountryOrigin { get; set; }
    
        public int CountryDestinationId { get; set; }
        public Country CountryDestination { get; set; }
    }
    

    EF 足够聪明,可以按照惯例计算 Id。如果您不希望遵循约定,您可以使用属性上的 [ForeignKey] 属性来配置 FK:

    [ForeignKey("Origin")]
    public int MyOriginId { get; set; }
    public Country Origin { get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      相关资源
      最近更新 更多