1

我对 NHibernate 和 .NET 框架还很陌生。

我想映射我的 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");
    }
}

当我只映射与 Subproject 类的关联时,一切正常,并且 Project.Subprojects 中 Subproject 类的所有实例都将正确存储到数据库中。当我对 ProjectTask 类使用第二个覆盖时,我得到以下异常:

---> NHibernate.HibernateException:数据库中已经有一个名为“ProjectId”的对象。无法创建约束。请参阅以前的错误。

---> System.Data.SqlClient.SqlException:数据库中已经有一个名为“ProjectId”的对象。

有谁知道,为什么会这样?

4

1 回答 1

3

Column您应该使用 a而不是 a映射您的项目引用ForeignKey

mapping.References<Project>(x => x.Project)
            .Column("ProjectId");
于 2010-11-23T08:31:24.990 回答