Hi all. I'm new to NHibernate so I apologize if this question is incredibly silly or basic, but I've been banging my head against the wall for the past day or so trying to figure this out.
I'm writing a unit test that will check if I am able to persist a User object to my database and retrieve it back. The User object has a list of Items that it must persist. The relationship from a User to an Item is a one-to-many relationship (i.e. a User may have many Items). Here is the User class:
Code:
public class User
{
public virtual int UserID { get; set; }
public virtual string UserName { get; set; }
public virtual IList<Item> Items { get; set; }
}
And here is the Item class
Code:
public class Item
{
public virtual int ItemID { get; set; }
public virtual User user { get; set; }
}
Here is the User.hbm.xml file:
Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Core" namespace="Core">
<class name="User" table="Users">
<id name="UserID">
<generator class="native" />
</id>
<bag name="Items" lazy="true" cascade="all-delete-orphan">
<key column="UserID" />
<one-to-many class="Item" />
</bag>
</class>
</hibernate-mapping>
And here is the Item.hbm.xml file:
Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Core" namespace="Core">
<class name="Item" table="Items">
<id name="ItemID">
<generator class="native" />
</id>
<many-to-one name="User" class="User" column="UserID" />
</class>
</hibernate-mapping>
Lastly, here is my unit test code:
Code:
[Test]
public void Can_Add_User()
{
User user = CreateTestUser1();
UserRepository userRepository = new UserRepository();
// Make sure user doesn't already exist in db
Assert.IsNull(userRepository.GetUserByUserName(user.Username);
// Add user to db
userRepository.SaveUser(user);
// Make sure user exists in db now
User retrievedUser = userRepository.GetUserByUserName(user.Username);
// This should cause the unit test to fail!
user.Items.Clear();
// Make sure some of the information was persisted correctly (arbitrarily chosen fields)
Assert.IsNotNull(retrievedUser);
Assert.IsNotNull(retrievedUser.UserID);
Assert.AreEqual(user.Items.Count, retrievedUser.Items.Count);
}
The CreateTestUser1 function simply instantiates a new User object. The SaveUser and GetUserByUserName functions use the "Save" and "UniqueResult" NHibernate functions.
Now, notice the "user.Items.Clear()" function. I would have expected this to cause the unit test to fail since "user" would now have 0 items and "retrievedUser" would have X items (where X is the number of items set in the CreateTestUser1 function). But it appears that any change I make to the "user" object also changes the "retrievedUser" object. I've stepped through this to test it out. I changed the "user"'s UserName property and sure enough, the "retrievedUser"'s UserName property changed as well.
Any ideas what could be causing this?