SORU
5 NİSAN 2011, Salı


Varlık Çerçevesi Kod İlk - iki Yabancı Anahtarları aynı tablo

Sadece ilk EF kod kullanmaya başladım, bu konuda toplam acemi değilim.

Takımlar ve Maçlar arasında ilişkiler yaratmak istedim: 1 = 2 takım (ev, misafir) ve maç sonucu. Kolay böyle bir model oluşturmak için olduğunu düşündüm, kodlama başladım:

public class Team
{
    [Key]
    public int TeamId { get; set;} 
    public string Name { get; set; }

    public virtual ICollection<Match> Matches { get; set; }
}


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

    [ForeignKey("HomeTeam"), Column(Order = 0)]
    public int HomeTeamId { get; set; }
    [ForeignKey("GuestTeam"), Column(Order = 1)]
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

Ve bir istisna olsun: The referential relationship will result in a cyclical reference that is not allowed. [ Constraint name = Match_GuestTeam ] . Nasıl böyle bir model, 2 aynı tablo için yabancı anahtarları ile birlikte oluşturabilir miyim ? TİA.

CEVAP
5 NİSAN 2011, Salı


Bunu deneyin:

public class Team
{
    public int TeamId { get; set;} 
    public string Name { get; set; }

    public virtual ICollection<Match> HomeMatches { get; set; }
    public virtual ICollection<Match> AwayMatches { get; set; }
}

public class Match
{
    public int MatchId { get; set; }

    public int HomeTeamId { get; set; }
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}


public class Context : DbContext
{
    ...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Match>()
                    .HasRequired(m => m.HomeTeam)
                    .WithMany(t => t.HomeMatches)
                    .HasForeignKey(m => m.HomeTeamId)
                    .WillCascadeOnDelete(false);

        modelBuilder.Entity<Match>()
                    .HasRequired(m => m.GuestTeam)
                    .WithMany(t => t.AwayMatches)
                    .HasForeignKey(m => m.GuestTeamId)
                    .WillCascadeOnDelete(false);
    }
}

Birincil anahtarlar, varsayılan kongre tarafından eşleştirilir. Takım maçları iki koleksiyonu var. Tek toplama iki Sayılı tarafından başvurulan olabilir. Maç bu kendini çok çok başvuran olmuyor çünkü silmek basamaklı olmadan eşleştirilir.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • BigDawsTv

    BigDawsTv

    20 HAZİRAN 2012
  • Dan Gately

    Dan Gately

    13 AĞUSTOS 2006
  • The Amazing Atheist

    The Amazing

    20 Kasım 2006