1
让我们挑选一个例子模型作为参考:插入NHibernate的对象,而获得其所有的孩子引用的对象
public class Cat{
public long Id;
public string Name;
public IEnumerable<Cat> Friends; //ManyToMany
}
注意,这可能是最简单的模型,我可以形容。
目前,为了插入新的Cat
及其Friends
,我必须首先获取完整的持久对象。例如..
Cat sally = Repository.GetByName("Sally").First(); //The first cat named Sally
Cat mary = new Cat{ Name="Mary, Friends = new Cat[] {sally} };
Repository.Save(mary); //Which is Session.Save(mary);
只要莎莉在当前范围内,这工作正常。但在网络环境中,考虑到我在MVC中工作,我不一定将所有持久对象保留在内存中。想想一个页面,我可以创建新的猫,并从多选列表中选择孩子...
如果MVC控制器返回我只有猫的ID(这是我想要的)我不能做下面,否则我得到一个重复的条目例外
Cat mary = new Cat{ Name="Mary, Friends = new Cat[] {new Cat{ Id = 1}, new Cat{Id=2}... };
Repository.Save(mary); //Boom, because it tries to persist the new children with duplicate IDs
相反,我必须
long[] ids;
IEnumerable<Cat> friends = from cat in Repository.Query() where Id in ids select cat; //Which does a SELECT query
Cat mary = new Cat{ Name="Mary", Friends = friends };
Repository.Save(mary); //Which runs fine;
现在我的问题是:因为在某个时间,我知道的集合的主键已经持续对象, 我怎么能够插入一个新对象,该对象引用了集合的对象而不查询数据库以获取它们全部?
我明白,NHibernate有缓存,所以经常查询Session
已知ID不会触发完整查询,但我想了解更多关于NHibernate的强大功能。
由于这个问题是出于示例的目的,不要介意,如果我不关心反比关系。