I have on top entity with many child entities.
Now, I want implement FindAll() method where I’m using this pattern with querying all my top entities to List. That’s fine but I then get all my child objects with it, Alert: Select N+1 in nhib. profiler.
After I get all my objects I send them to FromMyDomainModel method to extract values to ViewModel I need.
using (ITransaction transaction = session.BeginTransaction())
{
List<Property> data =
session.Query<Property>()//I don't need fetch
.ToList();
transaction.Commit();
return EntityViewModel.FromDomainModel(data);
}
Maybe there is better pattern so please feel free to post.
update: mapping code
from mapping you can figure it my entity code
public PropertyMap()
{
Table("Property");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Version);
Map(x => x.Created);
Map(x => x.Updated);
Map(x => x.Views);
....
Map(x => x.Price);
HasMany(x => x.Photos).KeyColumn("PropertyId").Cascade.All();
}
public PhotoMap()
{
Table("Photo");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.ImageData).CustomSqlType("VARBINARY(MAX)").Length(160000).Not.Nullable();
Map(x => x.ImageMimeType).Not.Nullable();
References(x => x.Property).Column("PropertyId");
}
To reduce the
select n+1problem you need to set thebatch-sizeNH3.2+ sets loading batch-size to 20 by default so if you can upgrade then I would recommend it. See here [NH-2593]
If you cannot upgrade and if are using XML mappings then do something like:-
If you are not using XML mappings then please post a mapping example.
edit based on your updated mapping
Try this and reprofile, you should see your n+1 reduce by a magnitude of 50
Also you can set this batch-size in the configuration before you build your session factory so it applies to all your collection fetching.