Here are the mappings:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="cs_nhibernate_test1"
namespace="cs_nhibernate_test1">
<class name="User" table="users">
<id name="Id" type="int">
<column name="Id" not-null="true" />
<generator class="native"/>
</id>
<property name="Name" column="Name" />
<property name="Age" column="Age" />
<bag name="Posts" inverse="true" cascade="all">
<key column="UserId" />
<one-to-many class="Post" />
</bag>
</class>
<class name="Post" table="posts">
<id name="Id" type="int">
<column name="Id" not-null="true" />
<generator class="native"/>
</id>
<property name="Text" column="Text" />
<many-to-one name="User" column="UserId" />
</class>
</hibernate-mapping>
Here’s the code:
public class User
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual int Age { get; set; }
public virtual IList<Post> Posts { get; set; }
public override string ToString()
{
return string.Format("User{{id={0}, name='{1}', age={2}}}", Id, Name, Age);
}
}
public class Post
{
public virtual int Id { get; set; }
public virtual string Text { get; set; }
public virtual User User { get; set; }
public override string ToString()
{
return string.Format("Post{{id={0}, text='{1}', user={2}}}", Id, Text, User);
}
}
static void Main(string[] args)
{
...
ISessionFactory sessionFactory = cfg.BuildSessionFactory();
using (ISession session = sessionFactory.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
for (int i = 0; i < 3; ++i)
{
var user = new User
{
Name = string.Format("John Smith #{0}", i + 1),
Age = 25 + i,
Posts = new List<Post>()
};
for (int j = 0; j < 3; ++j )
{
var post = new Post
{
Text = string.Format("qwerty {0} {1}", i, j)
};
user.Posts.Add(post);
}
session.SaveOrUpdate(user);
}
transaction.Commit();
}
foreach (User u in session.CreateCriteria(typeof (User)).List<User>())
{
Console.WriteLine(u);
foreach (Post post in u.Posts)
{
// post.User is always null!
Console.WriteLine(" {0}", post);
}
}
foreach (Post p in session.CreateCriteria(typeof(Post)).List<Post>())
{
// p.User is always null!
Console.WriteLine(p);
}
}
}
Post.User is always null. Already spent 3 hours. Where am I wrong?
Post.Userproperty and theUser.Postscollection is inverse, so no reference will be created in the database (if theposts.UserIdcolumn would be not null you would get an error on insert).User.Postscollection would be non-inverse, thePost.Userproperty would still be null. NHibernate doesn’t modify your objects on save (other than replacing the collections with its own implementations) and the criteria returns the same objects you just saved because they are in the session cache.