簡體   English   中英

EntityFramework中的一對多

[英]Double one-to-many in EntityFramework

我首先在實體框架代碼中遇到一對多類型的雙重關系問題。 看圖片: http : //i43.tinypic.com/5u2x03.png

在班級俱樂部,我有:

public virtual ICollection<Mecz> Hosts{ get; set; }
public virtual ICollection<Mecz> Gests{ get; set; }

課堂比賽:

public virtual Club Club { get; set; }

當更新數據庫時,我有3個外鍵,但我認為應該只有2個。有什么特殊的方法可以使這種關系正常工作?

使用Entity Framework Power Tools查看EF對您的設置的看法。

http://www.infoq.com/news/2013/10/ef-power-tools-beta4

右鍵單擊您的數據上下文類,然后執行Entity Framework-View Entity Data Model。

如果您在Mecz上具有導航屬性,並且還放入Id屬性,則可能會有所幫助。

public class Mecz {
    public int HostAtId{get; set;}
    public virtual Club HostAt{get; set;}
    public int GestAtId{get; set;}
    public virtual Club GestAt{get; set;}
}

然后,您不需要在比賽中加入俱樂部:您可以說

Match.Gest.GestAt

我自己解決了問題。 在我的回答下面,也許有人需要它。

比賽類別:

    public class Match
{
    [Key]
    public int MatchID { get; set; }

    public int HostID { get; set; }
    [ForeignKey("HostID")]
    public virtual Club Hosts{ get; set; }

    public int GestID { get; set; }
    [ForeignKey("GestID")]
    public virtual Club Gests{ get; set; }

}

俱樂部班級:

    public class Club
{
    public int ClubID { get; set; }

    public string ClubName{ get; set; }

    public virtual ICollection<Match> Host{ get; set; }
    public virtual ICollection<Match> Gest{ get; set; }
}

在OnModelCreating的MyDbContext中,我添加了以下代碼:

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<Match>()
        .HasRequired(x => x.Host)
        .WithMany(x => x.Host)
        .WillCascadeOnDelete(false);

        modelBuilder.Entity<Match>()
        .HasRequired(x => x.Gest)
        .WithMany(x => x.Gest)
        .WillCascadeOnDelete(false);
    }

暫無
暫無

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

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