Felipe Leusin
Felipe Leusin

Reputation: 20031

Problem with association when using EntityFramework

I'm currently testing EntityFramework 4.1.

My problem is, I have a Team class and a Game class.

class Team {
    string Name { get; set; }
}

class Game {
     Team HomeTeam { get; set; }
     Team AwayTeam { get; set; }
}

Still haven't found a way to map this. I've managed to do so using NHibernate but no luck with EF. Any pointers?

Upvotes: 0

Views: 121

Answers (1)

anon
anon

Reputation: 4608

This is maps cleanly for me:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Team>().HasKey(t => t.Name);

        modelBuilder.Entity<Game>().HasKey(
                        g => new { g.AwayTeamName, g.HomeTeamName });

        modelBuilder.Entity<Game>()
                        .HasRequired(g => g.HomeTeam)
                        .WithMany()
                        .HasForeignKey(g => g.HomeTeamName)
                        .WillCascadeOnDelete(true);

        modelBuilder.Entity<Game>()
                        .HasRequired(g => g.AwayTeam)
                        .WithMany()
                        .HasForeignKey(g => g.AwayTeamName)
                        .WillCascadeOnDelete(false);

        base.OnModelCreating(modelBuilder);
    }

Note that you cannot cascade both PK/FK relationships. If you were successful with NHib, you will know that cascading both would cause cycles.


EDIT: I guess I should include my POCOs:

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

public class Game
{
    internal string HomeTeamName { get; set; }
    public Team HomeTeam { get; set; }

    internal string AwayTeamName { get; set; }
    public Team AwayTeam { get; set; }
}

Note that you MUST have some sort of key on your POCOs, hence the need for the HomeTeamName and AwayTeamName. You can keep them internal if you want to hide them from the consuming code.

Upvotes: 1

Related Questions