可选的一对多关系

Optional One to many relationship

我正在尝试使用 fluent API 建立可选的一对多关系。但它似乎不起作用,因为我收到此错误:

InBuildingNavigator.Data.Models.ConnectionPointRoute_Segment: : Multiplicity conflicts with the referential constraint in Role 'ConnectionPointRoute_Segment_Target' in relationship 'ConnectionPointRoute_Segment'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

这是模型创建:

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ConnectionPointRoute>()
            .HasKey(c => new {c.ConnectionPointId, c.RouteId, c.SegmentId});

        modelBuilder.Entity<ConnectionPoint>()
            .HasMany(c => c.ConnectionPointRoutes)
            .WithRequired(x => x.ConnectionPoint)
            .HasForeignKey(c => c.ConnectionPointId);

        modelBuilder.Entity<Route>()
            .HasMany(c => c.ConnectionPointRoutes)
            .WithRequired(x => x.Route)
            .HasForeignKey(c => c.RouteId);

        modelBuilder.Entity<Segment>()
            .HasMany(c => c.ConnectionPointRoutes)
            .WithOptional(s => s.Segment)
            .HasForeignKey(s => s.SegmentId);
    }

这是模型:

public class ConnectionPointRoute
{
    public int ConnectionPointId { get; set; }
    public int RouteId { get; set; }
    public int? SegmentId { get; set; }
    public  int Position { get; set; }
    public ConnectionPoint ConnectionPoint { get; set; }
    public Route Route { get; set; }
    public Segment Segment { get; set; }
}
public class Segment
{
    public Segment()
    {
        ConnectionPointRoutes = new List<ConnectionPointRoute>();
    }

    public int SegmentId { get; set; }
    public int ConnectionPointIdEnd { get; set; }
    public string ConnectionName { get; set; }
    public string ConnectionInformation { get; set; }
    public string Image { get; set; }
    public string Direction { get; set; }
    public ICollection<ConnectionPointRoute> ConnectionPointRoutes { get; set; }
}

有什么想法吗?

这是因为您试图在 ConnectionPointRoute 上定义一个复合主键,其中包括可为空的 SegmentId。您不能在可为空的列上定义主键。