【问题标题】:How to Create two Foreign Keys in one Table pointing to the same Column in some table?如何在一个表中创建两个外键指向某个表中的同一列?
【发布时间】:2023-04-02 14:41:01
【问题描述】:

我有一个我想实现的数据库设计,这很难并且会出错“有多个 ForeignKeyAttributes 指向同一组属性”

我们有一个机场和航班,一个航班有一个指向其起飞机场的外键,以及另一个指向该航班要去的机场的外键。

但两个机场都在同一张表中。那里的 Flight 表有两个外键指向 Airport 表中的同一列

机场类

{
public class Airport
{
    [Key]
    public int Id { get; set; }

    [ForeignKey(nameof(Flight.ToAirportId))]
    public ICollection<Flight> ComingFlightsId { get; set; }

    [ForeignKey(nameof(Flight.FromAirportId))]
    public ICollection<Flight> GoingFlightsId { get; set; }
}}

飞行等级

{
public class Flight
{
    [Key]
    public int Id { get; set; }

    [ForeignKey(nameof(FromAirportId))]
    public Airport FromAirport { get; set; }
    public int FromAirportId { get; set; }

    [ForeignKey(nameof(ToAirportId))]
    public Airport ToAirport { get; set; }
    public int ToAirportId { get; set; }
}}

【问题讨论】:

  • 这里没有问题,你的代码出了什么问题?
  • 当我尝试迁移时出现错误“有多个 ForeignKeyAttributes 指向同一组属性”,我不知道出了什么问题
  • 我建议将此信息添加到问题中,以确保查看它的人确切知道您需要什么帮助!
  • 我认为机场不需要ForeignKeyAttribute,因为这些是多对一链接。 Airport 表没有指向 Flight 的外键。
  • 您为此使用 InversePropertyAttribtue:docs.microsoft.com/en-us/dotnet/api/…

标签: c# sql database-design foreign-keys ef-code-first


【解决方案1】:

就用这个吧:

public class Airport
{
  public int Id { get; set; }

  [InverseProperty("FromAirport")]
  public ICollection<Flight> ComingFlights { get; set; }

  [InverseProperty("ToAirport")]
  public ICollection<Flight> GoingFlights { get; set; }
}


public class Flight
{
   public int Id { get; set; }

   public int FromAirportId { get; set; }

   public int ToAirportId { get; set; }

   [ForeignKey(nameof(FromAirportId))]
   [InverseProperty("ComingFlights")]
   public Airport FromAirport { get; set; }


   [ForeignKey(nameof(ToAirportId))]
   [InverseProperty("GoingFlights")]
   public Airport ToAirport { get; set; }    
 }

【讨论】:

    【解决方案2】:

    我找到了我的问题的答案。 Inverse Property

    将此注释添加到 ICollection

    在我的例子中,Airport 类应该是这样的

    {
    public class Airport
    {
        [Key]
        public int Id { get; set; }
        public string Locatoin { get; set; }
    
    
        [InverseProperty(nameof(Flight.ToAirportId))]
        public ICollection<Flight> ComingFlightsId { get; set; }
    
        [InverseProperty(nameof(Flight.FromAirportId))]
        public ICollection<Flight> GoingFlightsId { get; set; }
    }}
    

    【讨论】:

      【解决方案3】:

      尝试在public ICollection&lt;Flight&gt; ComingFlightsId { get; set; }public ICollection&lt;Flight&gt; GoingFlightsId { get; set; }上使用virtual修饰符并从中删除ForeignKey属性

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-07
        • 1970-01-01
        • 2017-01-09
        • 2015-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多