簡體   English   中英

為多對多添加一對多連接

[英]Add a one-to-many connection to Many-to-Many

我與其他一些領域有很多關系。 但是因為有很多關系可以應用於其他關系的照片,我想分開它,所以我可以通過改變一對多的關系來改變它。 這是模型

public class Segment
{
    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; }
}
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; }
}

模型構建器看起來像這樣:

    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)
            .WithRequired(x => x.Segment)
            .HasForeignKey(c => c.SegmentId);
    }

這一切都適用於獲取項目,但由於某種原因,它不允許我發布新的路由,例如,它讓我得到錯誤:

“違反了多重約束。關系'InBuildingNavigator.Data.Models.Segment_ConnectionPointRoutes'的角色'Segment_ConnectionPointRoutes_Source'具有多重性1或0..1。”

有什么想法嗎?

修好了! 我的Post代碼中有一個錯誤,我添加了完整的子對象,這在我的情況下並沒有多大意義。

問我是否想要更詳細的解決方案!

還有兩件事要做:

  1. 我建議你使用額外的對象來實現多對多關系(如果你還沒有這樣做)。 這將使您可以更好地控制表名和您可能想要做的選擇。
  2. 對你的屬性使用virtual關鍵字,你不需要直接(對於你的集合) - 這將允許ef對它們實現延遲加載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM