c# - How to enable lazy loading of relations after INSERT in NHibernate -
i have 1 many relationship between 2 entities in nhibernate:
public class application { public string taskid { get; set; } // foreign key reference public task task { get; set; } // relation/navigation property }
the db.web.applications.create
method calls "saveorupdate" method of nhibernate session inside transaction.
the relavant mappings:
internal class applicationmap : classmap<application> { public applicationmap() : base() { schema(...); table(...); compositeid() .keyproperty(app => app.userid, "...") .keyproperty(app => app.taskid, "task_id") .keyproperty(app => app.transactionid, "..."); // relations references(app => app.task, "task_id") .foreignkey("taskid") .unique() .not.insert() .cascade.persist(); } } internal class taskmap : classmap<task> { public taskmap() { schema(..); table(...); id(task => task.id, "task_id"); hasmany(task => task.applications) .keycolumn("task_id"); } }
when wrote test against real database create new application
found navigation property not lazy loading after insert:
var app = new application(...) { taskid = "..." }; db.web.applications.create(app); db.savechanges(); var actual = db.web.applications.find(app.userid, app.taskid, app.transactionid); // actual.task null
the mappings working expect, after inserting new application
object, accessing task
property returns null
instead of lazy loading entity database. can done, , if so, how?
i think problem comes in way you've mapped application
class , it's corresponding task
object relation. think should map instead:
public class application { public task task { get; set; } // relation/navigation property } internal class applicationmap : classmap<application> { public applicationmap() : base() { schema(...); table(...); compositeid() .keyproperty(app => app.userid, "...") .keyreference(app => app.task, "task_id") .keyproperty(app => app.transactionid, "..."); } } internal class taskmap : classmap<task> { public taskmap() { schema(..); table(...); id(task => task.id, "task_id"); hasmany(task => task.applications) .keycolumn("task_id"); } }
there no need map specific id property foreign key relationships. map entity only. it's easier way. code above insertion this:
var app = new application(...) { task = session.load<task>(taskid) }; db.web.applications.create(app); db.savechanges(); var actual = db.web.applications.find(app.userid, app.taskid, app.transactionid);
Comments
Post a Comment