I have two simple classes named User and Role in a .Net Web Api project.
The User class is:
public class User
{
public virtual int Id { get; set; }
public virtual int RoleId { get; set; }
public virtual string Name { get; set; }
public virtual Role Role{ get; set; }
public User() { }
}
And the Role class is:
public class Role
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public Role() { }
}
The mappings using fluent are:
User:
public UserMap()
{
Table("plc_users");
Id(x => x.Id).Column("usr_id");
Map(x => x.RoleId).Column("rol_id");
Map(x => x.Name).Column("usr_name");
References(x => x.Role).Column("rol_id");
}
Role:
public RoleMap()
{
Table("plc_roles");
Id(x => x.Id).Column("rol_id");
Map(x => x.Name).Column("rol_name");
}
This is a unilateral relationship between User and Role. A User has a Role. Although a Role can be present in many Users, in this case, is not interesting to represent this in the Role class.
When I fetch a user from the database, the property "Role" is getting the wrong value. It should be:
{
"Id" : "2",
"RoleId" : "1",
"Name" : "Any",
"Role": {
"Id": "1",
"Name" : "Any"
}
}
But it's getting:
{
"Id" : "2",
"RoleId" : "1",
"Name" : "Any",
"Role": {
"__interceptor": {
"persistentClass": "NameSpaceForClass, , Version=1.0.0.0 [...]
"getIdentifierMethod": {
[...]
},
}
Observing the console for the SQL commands executed by NHibernate, the command for retrieving the role record is not been called.
So, what Am I missing here? Why the class Role is not been fetched properly according to it's domain definition?
UPDATE:
Thanks to the Radim Köhler answer, I realized that the problem wasn't with Fluent NHibernate, but with the "lazyloading serialization proxy hell".
Following his tips, I've found two new errors:
The first:
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'
And the inner:
Could not initialize proxy - no Session.
I'm using a session per action scope which means that the session is started at the begining of the action and closed at the end. From that, I started to try several ways to understand why the session was closing before the Json serialization. Lots of configurations later, I noticed that while in debug mode everything worked fine. And that was weird.
Anyway, I wasn't getting anywhere so I decided to turn off the lazyload mode, like this:
References(x => x.Role).Column("rol_id").ReadOnly().Not.LazyLoad();
This is not the solution. But solves the problem while I'm stuck in finding out why the session works only in debug mode.