【问题标题】:How can you map a collection of strings in NHibernate using a many-to-many relationship?如何使用多对多关系映射 NHibernate 中的字符串集合?
【发布时间】:2009-07-11 20:58:00
【问题描述】:

给定以下固定域模型:

public class Sentence {
    public int Id { get; private set; }
    public string Author { get; set; }
    public string[] Words { get; set; }
}

以及以下建议的规范化数据库架构:

create table Sentence (
    Id int identity(1,1) not null primary key,
    Author varchar(450)
)
create table Word (
    Id int identity(1,1) not null primary key,
    Value varchar(450) not null unique
)
create table Sentence_Word (
    SentenceId int foreign key references Sentence (Id),
    WordId int foreign key references Word (Id),
    SortIndex int not null,
    primary key (SentenceId, WordId),
    unique (SentenceId, SortIndex)
)

您将如何创建 NHibernate 映射文件?

如果我们可以添加另一个域实体Word 然后将Sentence 上的Words 属性更改为Word[] 而不是string[](这将是标准的多对多实体关系),但属性的string[]类型是必需的,不能更改。

这个问题和another StackOverflow question类似,只是需要使用多对多的关系来进行适当的数据规范化(词的集合比较小,而组合成句子的组合很大),所以不是立即清楚如何应用标准的基于值的集合。

【问题讨论】:

    标签: nhibernate nhibernate-mapping


    【解决方案1】:

    您可以按照您的建议添加域实体 Word,实现 Word on Sentence 的集合,并继续将 Word[] 数组公开为 string[]。每次访问属性时,只需从 Word 集合动态构建 Word[] 数组。如果性能是一个问题,您可以缓存并仅在 Word 集合更改时重建 Word[] 数组。

    如果我们可以添加另一个域实体 Word,然后将 Sentence 上的 Words 属性更改为 Word[] 而不是 string[](这将是标准的多对多实体关系),这将很容易,但是属性的 string[] 类型是必需的,不能更改。

    【讨论】:

    • 我实际上已经开始做类似的事情了。不幸的是,“句子”类不容易更改以添加另一个字段,所以我正在尝试添加一个带有附加属性的句子的子类,覆盖 Words,并适当更新 getter 和 setter 以保留这两个字段同步中。但是,为了从 string[] 动态填充 Word[],子类需要知道持久层以加载 Word 实体——我试图维护持久无知的域对象以实现真正透明的持久性,并希望避免这样的事情。
    • 两年内没有替代答案,这足以让我在两年前走上正确的道路,正如评论所言,将其标记为已接受的答案。
    猜你喜欢
    • 2012-06-12
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多