views:

15

answers:

0

Hello all,

I have the 2 following classes:

public class Player : BaseEntity<int, Player>
{
    public string FirstName
    {
        get; set;
    }

    public string LastName
    {
        get; set;
    }

    public int Number { get; set; }
    public IList<Team> Teams { get; set; }

    public void AddTeam(Team team)
    {
        Teams.Add(team);
        team.Players.Add(this);
    }
}

and

public class Team : BaseEntity<int,Team>
{
    public string Name { get; set; }
    public Sex Sex { get; set; }
    public IList<PlayerTeamNumber> Players { get; set; }

    public void AddPlayer(Player player)
    {
        Players.Add(player);
        player.Teams.Add(this);
    }
}

and their mappings:

public class PlayerMap : ClassMap<Player>
{
    public PlayerMap()
    {
        Table("Players");

        Id(p => p.Id)
            .GeneratedBy.Increment();

        Map(p => p.FirstName)
            .Not.Nullable()
            .UniqueKey("Players_Unique_FirstName_LastName");

        Map(p => p.LastName)
            .Not.Nullable()
            .UniqueKey("Players_Unique_FirstName_LastName");

        Map(p => p.Number);

        HasManyToMany(p => p.Teams)
            .Cascade.All();
    }
}

and

public class TeamMap : ClassMap<Team>
{
    public TeamMap()
    {
        Table("Teams");

        Id(t => t.Id)
            .GeneratedBy.Increment();

        Map(t => t.Name)
            .Not.Nullable()
            .UniqueKey("Teams_Unique_Name_Sex");

        HasManyToMany(t => t.Players)
            .Cascade.All();
    }
}

I would like to add a Number field to the table which will be generated by the HasManyToMany relationship, so that a player can have a different number if it belongs to multiple teams.

After a bit of reading, I've found an answer telling that a true many to many relationship doesn't have more fields than those referencing the foreign keys, and that I should create an intermediate entity between Player and Team.

I'd like you to confirm this :)

And if you confirm, would such an intermediate entity would look like this?

public class PlayerTeamNumber
{
    public PlayerTeamNumber(Player player, Team team, int playerNumber)
    {
        Player = player;
        Team = team;
        PlayerNumber = playerNumber;
    }

    public int PlayerNumber { get; set; }
    public Player Player { get; set; }
    public Team Team { get; set; }
}

public class PlayerTeamNumberMap : ClassMap<PlayerTeamNumber>
{
    public PlayerTeamNumberMap()
    {
        Table("PlayerTeamNumbers");

        Map(ptn => ptn.PlayerNumber);

        References(ptn => ptn.Player);

        References(ptn => ptn.Team);
    }
}

And then, should I replace the type of Team.Players and Player.Teams be of that type, and of course change the HasManyToMany mappings to HasMany only?

Thanks in advance

Mike

related questions