我有一个父子关系,目前,只有每个孩子对父母的引用存在(子表上有一个外键列)。我想向父级添加一个只读的 IEnumerable 属性,但我没有这样做。
public class ProjectData : Entity
{
public virtual long Id {get;set;}
private readonly IList<BranchData> _branches = new List<BranchData>();
public virtual IEnumerable<BranchData> Branches
{
get { return _branches.AsReadOnly(); }
}
}
public class BranchData : Entity
{
puplic virtual long Id {get;set;}
public virtual ProjectData ProjectData { get; set; }
}
public class BranchDataMapping : ClassMapping<BranchData>
{
public BranchDataMapping()
{
ManyToOne(x => x.ProjectData, mapper => { });
}
}
public class ProjectDataMapping : ClassMapping<ProjectData>
{
public ProjectDataMapping()
{
Bag(data => data.Branches,
mapper =>
{
mapper.Access(Accessor.ReadOnly);
mapper.Inverse(false);
}, relation => relation.OneToMany());
}
}
表名和列名是按约定创建的。当我创建并保存带有父属性集的新 BranchDate 时,它不会出现在父级的 Branches 集合中。
我缺少什么设置?
我已经通过代码和http://notherdev.blogspot.cz/2012/02/nhibernates-mapping-by-code-summary.html阅读了双向 NHibernate 映射,但我仍然无法正确设置它。
编辑:验证此行为的代码
[Test]
public void CanSaveAndLoadBranch()
{
var session = InMemoryDatabase.GetSession();
var project = new ProjectData {Name = "ratata"};
var branch = new BranchData {ProjectData = project};
using (var tx = session.BeginTransaction())
{
session.Save(project);
session.Save(branch);
tx.Commit();
}
var branches = project.Branches;
//branches are empty
var freshProject = session.Query<ProjectData>().Where(x => x.Id == project.Id).First();
var freshBranches = freshProject.Branches;
//branches are empty here, too
var fetched = session.Query<ProjectData>().Where(x => x.Id == project.Id).FetchMany(x => x.Branches).First();
var fetchedBranches = fetched.Branches;
//branches are empty here, too
var queriedOn = session.Query<ProjectData>().Where(x => x.Branches.Any()).ToList();
//this does return the project, but Branches property is still empty
}