2015-09-25 74 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完美的作品:) –