【问题标题】:Mapping template / instance tables with NHibernate使用 NHibernate 映射模板/实例表
【发布时间】:2011-11-29 19:45:08
【问题描述】:

我正在尝试将 NHibernate 与在概念上等同于以下内容的数据库一起使用:

CREATE TABLE Survey(ID int, SurveyName varchar(max))
CREATE TABLE Question(ID int, QuestionText varchar(max))
CREATE TABLE SurveyQuestion(SurveyID int, QuestionID int, Order int, Required bit)

CREATE TABLE AnsweredSurvey(ID int, SurveyID int, AnsweredBy varchar(max))
CREATE TABLE AnsweredQuestion(ID int, AnsweredSurveyID int, QuestionID int, Answer varchar(max))

每当用户进行调查时,AnsweredSurvey/AnsweredQuestion 表都会从模板表中填充。这是由另一个应用程序执行的,所以我只从这些表中读取数据。我无法控制数据或架构。

我遇到问题的实体是:

class AnsweredQuestion {
    int Id;
    AnsweredSurvey AnsweredSurvey;
    SurveyQuestion SurveyQuestion;
}

请注意,它有一个 SurveyQuestion 类型的属性,而不是普通的 Question。我希望能够根据 AnsweredQuestion 的 QuestionID 和父 AnsweredSurvey 的 SurveyID 填充此属性。在 NHibernate 中是否有一种直接的方法可以以这种方式映射这些实体?我正在使用 FluentNHibernate,但纯 HBM 解决方案至少会为我指明正确的方向。

为完整起见,以下是其他实体:

class Survey {
    int Id;
    string SurveyName;
    IEnumerable<SurveyQuestion> SurveyQuestions;
}

class Question {
    int Id;
    string QuestionText;
}

class SurveyQuestion {
    Survey Survey;
    Question Question;
    int Order;
    bool Required;
}

class AnsweredSurvey {
    int Id;
    Survey Survey;
    IEnumerable<AnsweredQuestion> AnsweredQuestions;
}

感谢您的宝贵时间!

【问题讨论】:

    标签: .net sql sql-server nhibernate fluent-nhibernate


    【解决方案1】:

    您的模型和架​​构的问题在于映射 SurveyQuestion 实体/表,因为它有一个复合键,您希望将其映射到两个多对一关联。这可以做到,但我从未使用过它。

    使用流畅的 nhibernate 的示例:

    SurveyQuestionMap()
    {
       CompositeId() 
         .KeyReference(x => x.Survey, "SurveyID")
         .KeyReference(x => x.Question, "QuestionID");
    
      // the rest
    }
    

    其他类应该没问题。 例如:

     AnsweredSurveyMap()
     { 
         Id(x => x.Id)
         References(x => x.Survey);
         HasMany(c => c.AnsweredQuestions)
           .Inverse()
           .Cascade.All()
           .KeyColumn("AnsweredSurveyID");
    }
    

    您可能需要根据配置的 fluent nhibernate 约定设置指定更多的键列/表。

    【讨论】:

    • 问题是,我想从 AnsweredQuestion 中引用 SurveyQuestion,但是 AnsweredQuestion 没有 SurveyID。为了获得 SurveyID,我必须遵循与 AnsweredSurvey 的关联,但我不知道如何在映射类中以声明方式执行此操作。
    猜你喜欢
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多