【发布时间】:2015-04-01 13:46:34
【问题描述】:
我在 NHibernate 中的两个实体之间存在一对多关系:
public class Application
{
public string TaskId { get; set; } // Foreign key reference
public Task Task { get; set; } // The relation/navigation property
}
db.Web.Applications.Create 方法只是在事务中调用 NHibernate 会话的“SaveOrUpdate”方法。
相关映射:
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");
}
}
当我针对真实数据库编写测试以创建新的Application 时,我发现导航属性在插入后没有延迟加载:
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 is null
映射按预期工作,但在插入新的Application 对象后,访问Task 属性会返回null,而不是从数据库中延迟加载该实体。这可以做到吗?如果可以,怎么做?
【问题讨论】:
标签: c# nhibernate orm fluent-nhibernate