EF可选一对多多重性错误

本文关键字:多重性 错误 一对多 EF | 更新日期: 2023-09-27 18:14:37

我有一个非常简单的模式,进一步简化了这个问题

Table: Airport
IATA char(3) Primary Key
Name varchar(20)
Table: Airport_Terminal
IATA char(3) (comp key1)
TerminalName (comp key2)
POCOs
public sealed class Airport
{
    [Key]
    public string IATA { get; set; }       
    public string Name { get; set; }
    public ICollection<AirportTerminal> Terminals { get; set; }
}
    public class AirportTerminal
{
    [Key, Column(Order = 0)]
    public string IATA { get; set; }
    [Key, Column(Order = 1)]
    public string Terminal { get; set; }
    public Airport Airport { get; set; }
}

AirportTerminal配置

modelBuilder.Entity<AirportTerminal>()
    .HasOptional<Airport>(s => s.Airport)
    .WithMany(s => s.Terminals)
    .HasForeignKey(s => s.IATA);

有些机场(在我的应用程序中)有多个终端,有些没有。我只是想在为给定机场定义了terminal时对Terminals属性做出反应。如果我为每个机场输入一条记录,则此配置有效。但是当我试图查找任何机场时,我得到:

 "One or more validation errors were detected during model generation: Multiplicity conflicts with the referential constraint in Role 'AirportTerminal_Airport_Target' in relationship 'AirportTerminal_Airport'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'."

研究表明,当可选成员上存在非空属性时,会发生此错误,因此不能将其设置为空。AirportTerminal包含两个字符串,可为空。

任何想法?

EF可选一对多多重性错误

考虑只对表使用key。这是最好的,而不是多键。放置索引约束以确保属性IATATerminal的唯一性。

少:

public sealed class Airport
{
    [Key]
    public Guid Id { get; set; }
    public string IATA { get; set; }       
    public string Name { get; set; }
    public ICollection<AirportTerminal> Terminals { get; set; }
}
public class AirportTerminal
{
    [Key]
    public Guid Id { get; set; }
    public string IATA { get; set; }
    public string Terminal { get; set; }
    public Airport Airport { get; set; }
    public Guid? AirportId { get; set; }
}
配置:

modelBuilder.Entity<AirportTerminal>()
    .HasOptional<Airport>(s => s.Airport)
    .WithMany(s => s.Terminals)
    .HasForeignKey(s => s.AirportId);