可选的一对多关系

时间:2016-05-25 14:23:40

标签: c# asp.net-mvc entity-framework fluent

我正在尝试使用流畅的API制作和可选的一对多关系。但是,当我收到此错误时,它似乎无法正常工作:

  

InBuildingNavigator.Data.Models.ConnectionPointRoute_Segment ::多重性与角色' ConnectionPointRoute_Segment_Target'中的参照约束冲突。在关系' ConnectionPointRoute_Segment'。由于从属角色中的所有属性都是不可为空的,因此主要角色的多样性必须为' 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; }
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这是因为您尝试在ConnectionPointRoute上定义包含可以为空的SegmentId的复合主键。您无法在可空列上定义主键。