【问题标题】:Optional One to many relationship可选的一对多关系
【发布时间】:2016-09-23 05:29:46
【问题描述】:

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

InBuildingNavigator.Data.Models.ConnectionPointRoute_Segment: : 多重性与关系“ConnectionPointRoute_Segment”中角色“ConnectionPointRoute_Segment_Target”中的引用约束冲突。由于 Dependent Role 中的所有属性都不可为空,因此 Principal Role 的复数必须为“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; }
}

有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 谢谢!就是这样!
    猜你喜欢
    • 2022-11-26
    • 1970-01-01
    • 2013-06-10
    • 2013-11-19
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多