我有一个名为Strategy的实体,另一个叫做Team。两者都使用多对多关系进行映射:
public class Team : BaseEntity<Team>
{
private readonly IList<Strategy> allStrategies = new List<Strategy>();
public void AddStrategy(Strategy strategy)
{
allStrategies.Add(strategy);
strategy.AddTeam(this);
}
public void RemoveStrategy(Strategy strategy)
{
allStrategies.Remove(strategy);
strategy.RemoveTeam(this);
}
}
public class TeamMap : ClassMap<Team>
{
public TeamMap()
{
HasManyToMany<Strategy>(Reveal.Member<Team>("allStrategies"))
.Cascade.SaveUpdate()
.Access.CamelCaseField()
.Table("TeamStrategies");
}
}
public class StrategyMap : ClassMap<Strategy>
{
public StrategyMap()
{
HasManyToMany<Team>(Reveal.Member<Strategy>("allTeams"))
.Inverse()
.Cascade.SaveUpdate()
.Access.CamelCaseField()
.Table("TeamStrategies");
}
}
这是从NH产生奇怪行为的单元测试:
[Fact]
public void Test()
{
using (var session = Kernel.Get<ISession>())
{
var team = new Team("JAO", Sex.Male);
var repository = new TeamsRepository(session);
repository.Save(team);
var sA1 = new Strategy("Horn", StrategyType.Attack);
var sA2 = new Strategy("Shirt", StrategyType.Attack);
session.Save(sA1);
session.Save(sA2);
session.Flush();
team.AddStrategy(sA1);
team.AddStrategy(sA2);
repository.SaveOrUpdate(team);
session.Flush();
team.RemoveStrategy(sA1);
repository.SaveOrUpdate(team);
session.Flush();
Assert.Equal(2, session.Query<Strategy>().Count());
Assert.Equal(1, session.Query<Team>().Count());
}
}
以下是NH在最后一个session.Flush()上生成的查询:
NHibernate:DELETE FROM TeamStrategies WHERE Team_id = @ p0; @ p0 = 1 [Type:Int32(0)]
NHibernate:INSERT INTO TeamStrategies(Team_id,Strategy_id)VALUES(@ p0,@ p1); @ p0 = 1 [Type:Int32(0)],@ p1 = 2 [Type:Int32(0)]
为什么NH在插入那些尚未删除的行之前会删除所有TeamStrategies行?
如何使用包含TeamId和StrategyId上的过滤器的WHERE子句进行单个DELETE?
我在谷歌上搜索我的问题,这可能与Equals和GetHashCode函数有关。
如果可以提供帮助,我是从here获得的。
我试图在两边改变级联的价值,但我仍然无法正常工作:'(
有人可以帮忙吗?或许这是正常行为?但这很奇怪......
提前致谢
麦克
答案 0 :(得分:3)
我认为您需要将收藏集映射为<set>
而不是<bag>
,以获得您所追求的功能。