Skip to content

Instantly share code, notes, and snippets.

@AlexCuse
Created January 15, 2012 00:59
Show Gist options
  • Save AlexCuse/1613670 to your computer and use it in GitHub Desktop.
Save AlexCuse/1613670 to your computer and use it in GitHub Desktop.
Limiting Collection Contents w/ NHibernate
[Test]
public void Limit_Collection_Contents_Criteria() {
var pepperoni = new Topping { Name = "pepperoni", Type = "meat" };
var cheese = new Topping { Name = "mozzarella", Type = "dairy" };
var cheesePizza = new Pizza() { Crust = "deep dish", Sauce = "red" }
.WithTopping(cheese);
var pepperoniPizza = new Pizza() { Crust = "deep dish", Sauce = "red" }
.WithTopping(cheese)
.WithTopping(pepperoni);
using (var tran = session.BeginTransaction()) {
session.Save(pepperoni);
session.Save(cheese);
session.Save(cheesePizza);
session.Save(pepperoniPizza);
tran.Commit();
}
session.Evict(pepperoniPizza); // can't have pepperoni pizza in cache, or it will be used with full topping collection populated
var pizzasWithCheese =
session.CreateCriteria<Pizza>("p")
.CreateCriteria("p.Toppings", "t", NHibernate.SqlCommand.JoinType.LeftOuterJoin, Expression.Eq("t.Topping.Id", cheese.Id))
.List<Pizza>();
Assert.AreEqual(2, pizzasWithCheese.Count);
foreach (var p in pizzasWithCheese) {
Assert.IsTrue(p.Toppings.Count == 1);
}
}
[Test]
public void Limit_Collection_Contents_QueryOver() {
var pepperoni = new Topping { Name = "pepperoni", Type = "meat" };
var cheese = new Topping { Name = "mozzarella", Type = "dairy" };
var cheesePizza = new Pizza() { Crust = "deep dish", Sauce = "red" }
.WithTopping(cheese);
var pepperoniPizza = new Pizza() { Crust = "deep dish", Sauce = "red" }
.WithTopping(cheese)
.WithTopping(pepperoni);
using (var tran = session.BeginTransaction()) {
session.Save(pepperoni);
session.Save(cheese);
session.Save(cheesePizza);
session.Save(pepperoniPizza);
tran.Commit();
}
session.Evict(pepperoniPizza); // can't have pepperoni pizza in cache, or it will be used with full topping collection populated
var pizzasWithCheese = session.QueryOver<Pizza>()
.JoinQueryOver<ToppingUse>(p => p.Toppings, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
.Where(tu => tu.Topping == cheese)
.List<Pizza>();
Assert.AreEqual(2, pizzasWithCheese.Count);
foreach (var p in pizzasWithCheese) {
Assert.IsTrue(p.Toppings.Count == 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment