1
我對NHibernate和.NET框架相當新穎。用Fluent NHibernate自動映射創建多個雙向一對多關聯
我想映射我的Project類,它具有一對多關係Subproject和ProjectTask類。
public class Project : ProjectItem
{
public virtual IList<Subproject> Subprojects { get; set; }
public virtual IList<ProjectTask> Tasks { get; set; }
[NotNull]
public virtual ProjectStatus Status { get; set; }
public Project()
{
Subprojects = new List<Subproject>();
Tasks = new List<ProjectTask>();
Status = new ProjectStatus();
}
public virtual void AddSubProject(Subproject subproject)
{
subproject.Project = this;
Subprojects.Add(subproject);
}
public virtual void RemoveSubProject(Subproject subproject)
{
Subprojects.Remove(subproject);
}
public virtual void AddTask(ProjectTask task)
{
task.Project = this;
Tasks.Add(task);
}
public virtual void RemoveTask(ProjectTask task)
{
Tasks.Remove(task);
}
}
public class ProjectTask : ProjectItemTask
{
[NotNull]
public virtual Project Project { get; set; }
}
public class Subproject : ProjectItem
{
[NotNull]
public virtual Project Project { get; set; }
}
我的實體繼承了抽象基類的Id屬性。
我用自動映射到覆蓋重新定義我的映射:
public class ProjectMappingOverride : IAutoMappingOverride<Project>
{
public void Override(AutoMapping<Project> mapping)
{
mapping.HasMany<Subproject>(x => x.Subprojects)
.Cascade.All()
.Inverse()
.Not.LazyLoad()
.AsBag();
mapping.HasMany<ProjectTask>(x => x.Tasks)
.Cascade.All()
.Inverse()
.Not.LazyLoad()
.AsBag();
mapping.HasOne<ProjectStatus>(x => x.Status)
.Cascade.All()
.Not.LazyLoad();
}
}
public class SubprojectMappingOverride : IAutoMappingOverride<Subproject>
{
public void Override(AutoMapping<Subproject> mapping)
{
mapping.References<Project>(x => x.Project)
.ForeignKey("ProjectId");
}
}
public class ProjectTaskMappingOverride : IAutoMappingOverride<ProjectTask>
{
public void Override(AutoMapping<ProjectTask> mapping)
{
mapping.References<Project>(x => x.Project)
.ForeignKey("ProjectId");
}
}
當我只用映射子項目課堂上的一切協會工作正常,在Project.Subprojects子項目類的所有實例都將被存儲到數據庫正確。當我使用ProjectTask類的第二個覆蓋時,出現以下異常:
---> NHibernate.HibernateException:數據庫中已有一個名爲'ProjectId'的對象。無法創建約束。查看以前的錯誤。
---> System.Data.SqlClient.SqlException:數據庫中已經有一個名爲'ProjectId'的對象。
有誰知道,爲什麼會發生這種情況?
呀你的項目引用映射,真正幫助!非常感謝! – dasnervtdoch 2010-11-23 10:41:25