EF可选一对多重误差

时间:2015-09-25 19:24:18

标签: c# entity-framework entity

我有一个非常简单的架构,针对这个问题进一步简化

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);

有些机场(在我的应用程序中)有多个终端,有些则没有。当为给定机场定义了终端时,我只想对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'."

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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

考虑仅使用表的键。这是最好的而不是多个键。放置索引约束以确保属性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);