1

让我们选择一个示例模型作为参考:

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);

只要 sally 在当前范围内,它就可以正常工作。但是在 web 环境中,考虑到我在 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 的强大功能。

由于该问题是出于示例目的,因此请不要介意我不关心反向关系。

4

1 回答 1

1

由于您有 id,您需要做的就是使用session.Load获取引用而不从数据库加载它们。

只需将您的第二行更改为以下内容:

var friends = from id in ids select session.Load<Cat>(id);
于 2013-05-04T23:11:43.887 回答