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 us开发者_Go百科ing NHibernate but no luck with EF. Any pointers?
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.
精彩评论