开发者

Add to Nhibernate collection without initializing the collection

开发者 https://www.devze.com 2023-03-26 12:46 出处:网络
I have an entity called a Meter (Think an electric meter). The meter has a collection of Data Points. Every 15 minutes or so a new data point is added to the meter. The meter has a collection of thes

I have an entity called a Meter (Think an electric meter).

The meter has a collection of Data Points. Every 15 minutes or so a new data point is added to the meter. The meter has a collection of these data points.

I would like to code this up such as Meter myMeter = session.get<Meter>(id) and then myMeter.AddDataPoint(point) then session.Update(myMeter). Internally the Meter class has a collection (IESI.ISet<DataPoint>). However when adding to this collection I am thinking that NHibernate is going to first have to initialize the collection and load it from the database. The problem is there are going to be hundreds of thousands of items in this collection and it just won't be performant. So is it possible to code this up so that NHiberante will blindly add to the collection, without loading all of its values.

The DataPoint class has a many-to-one mapping to the Meter, a开发者_开发知识库nd the Meter has a set mapping of DataPoints.


1) You can remove set mapping from Meter class. This way you will never be hit with accidentally loading thousands data points. Later when you need to know all DataPoints for Meter you can load it dynamically. Looks like you will need subset of data points most of the time (data points for Meter X for August).

List<DataPoint> dp = DataPointsRepository.FindByMeter(Meter meter)
List<DataPoint> dp = DataPointsRepository.FindByMeter(Meter meter, DateRange range)

DataPoint will still need many-to-one relationship to meter in order to be properly associated and saved.

2) You can try to use 'bag' instead of 'set' but be careful to not call methods like obj.MyBag.Size() Related question: Hibernate - How to persist a new item in a Collection without loading the entire Collection


The semantics of the ISet implementation call for NHibernate to pull the full collection of items so that it can verify that the point that you're trying to add is indeed unique. I don't think there's a way around this other than to check the data/persist it independent of the meter.

Something along the lines of (using QueryOver):

var pointExists = session.QueryOver<DataPoint>().Where(p => p.Id==id /* etc */).Any();

if (!pointExists) {
    session.Save(dataPoint);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消