2015-09-25 73 views
0

我有一個非常簡單的模式,進一步對這個問題簡化EF可選一對多多重錯誤

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

一些機場(在我的應用程序)有多個終端和一些不要。我只是想在終端爲特定機場定義時對終端屬性做出反應。如果我爲每個機場輸入單個記錄,則此配置有效。但是,當我試圖查找任何一個機場,我得到:

"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

考慮只使用表的鍵。這是最好的,而不是多個關鍵。放置索引約束以確保屬性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); 
+0

當你在回答這個問題。我確實做到了。謝謝。這個def完美的作品:) –