Hello everybody! I try to use NHibernate.Linq to query from database and catch NullReferenceExceprion:
Code:
[Test]
public void Should_Get_By_Dict_Value()
{
using (ISession s = NHibernateHelper.GetCurrentSession())
{
var queryable = s.Linq<A>();
var first = queryable.First(a => a.Items["first"].Name == "first b");
Assert.That(first, Is.Not.Null);
}
}
But this work correctly:
Code:
[Test]
public void Should_Get_By_Dict_Value_Work()
{
using (ISession s = NHibernateHelper.GetCurrentSession())
{
var queryable = s.Linq<A>();
/*---->*/ var list = queryable.ToList(); /*<----*/
var first = list.First(a => a.Items["first"].Name == "first b");
Assert.That(first, Is.Not.Null);
}
}
I think this is the bag or NHibernate.Linq don't support lazy loading......
A class implementation, mapping and test:
Code:
public class A
{
private int? _id;
private string _name;
private IDictionary<string, B> _items;
public A() { }
public int? Id
{
get { return _id; }
set { _id = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public IDictionary<string, B> Items
{
get { return _items; }
set { _items = value; }
}
}
public class B
{
private int? _id;
private string _name;
public B() { }
public int? Id
{
get { return _id; }
set { _id = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
}
Mapping file
Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHTest" namespace="NHTest" default-lazy="false">
<class name="A" table="a">
<id name="Id" column="id" unsaved-value="null">
<generator class="native" />
</id>
<property name="Name" column="aname" />
<map name="Items" cascade="all-delete-orphan">
<key column="a_id" />
<index column="idx" type="String" />
<one-to-many class="B" />
</map>
</class>
<class name="B" table="b" lazy="false">
<id name="Id" column="id" unsaved-value="null">
<generator class="native" />
</id>
<property name="Name" column="aname" />
</class>
</hibernate-mapping>
Test:
Code:
[Test]
public void Simple()
{
A a = new A();
a.Name = "first generic type";
a.Items = new Dictionary<string, B>();
B firstB = new B();
firstB.Name = "first b";
B secondB = new B();
secondB.Name = "second b";
a.Items.Add("first", firstB);
a.Items.Add("second", secondB);
using (ISession s = NHibernateHelper.GetCurrentSession())
{
s.SaveOrUpdate(a);
s.Flush();
Assert.IsNotNull(a.Id);
Assert.IsNotNull(firstB.Id);
Assert.IsNotNull(secondB.Id);
var query = from v in s.Linq<A>()
where v.Id == a.Id
select v;
a = query.FirstOrDefault();
B thirdB = new B();
thirdB.Name = "third B";
a.Items.Add("third", thirdB);
Assert.AreEqual(3, a.Items.Count, "3 items in the map now");
s.Flush();
a = s.Load<A>(a.Id);
a.Items["second"] = a.Items["third"];
s.Flush();
}
}