Hello everybody,
would you mind help me to better understand what to do with the relationship between my entities and NHibernate?
I have some difficulties to understand what operations I need to do by hand, and what operations NHibernate will do for me (or not).
I have these 2 entities:
public class Position : BaseEntity<int, Position>
{
private IList<Player> allPlayers = new List<Player>();
public Position()
{
}
public Position(string name, int number)
: this()
{
Name = name;
Number = number;
}
public string Name { get; set; }
public int Number { get; set; }
}
and
public class Player : BaseEntity<int, Player>
{
public Player()
{
Visible = true;
}
public Player(string firstName, string lastName, int defaultNumber, Sex sex = Sex.Male, Position defaultPosition = null)
: this()
{
FirstName = firstName;
LastName = lastName;
DefaultNumber = defaultNumber;
Sex = sex;
DefaultPosition = defaultPosition;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public Position DefaultPosition { get; set; }
}
Here are the fluent mappings:
public class PositionMap : ClassMap<Position>
{
public PositionMap()
{
Id(pp => pp.Id)
.GeneratedBy.Increment();
Map(pp => pp.Name)
.Not.Nullable();
Map(pp => pp.Number)
.Not.Nullable();
HasMany<Player>(Reveal.Member<Position>("allPlayers"))
.Access.CamelCaseField();
}
}
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");
References(p => p.DefaultPosition);
}
}
As you can see, one player has one position, but may have no position (so DefaultPosition is nullable).
Here are my questions:
- When I associate a position to a player's DefaultPosition, I have to do this through helper methods on Position? (like AddPlayer, DeletePlayer...)
I'd like, when I delete a position, that all the players who have this position, have instead a null DefaultPosition.
Do I have to clear manually the field allPlayers of the position, and manually set null to all associated player's DefaultPosition, or can NHibernate take care of this for me?
Why does NHibernate only does a DELETE FROM Positions WHERE Id... and doesn't update the field DefaultPOsition of the concerned players? I've tried to add a Cascade.Delete on the HasMany in PositionMap, but that doesn't change anything. Do I have to run a custom query which does that?
Thanks in advance