nhibernate将许多行映射到一个对象

时间:2011-05-26 08:48:19

标签: nhibernate fluent-nhibernate mapping nhibernate-mapping

我有一个相当困难的映射问题。

编辑:重新制定的descritpion

由于历史原因,文本不作为文本存储在列中,而是保存在表中。我有几个表格具有以下结构:

TABLE SomeEntityTexts
(
  id serial NOT NULL,
  key character varying(10),      // \
  linenumber integer,             // / unique constraint
  type smallint,
  length smallint,                // actual length of content string
  content character varying(80),
  PRIMARY KEY (id)
)

文本被保存为具有任意长度的行,每个实体都不同,有时甚至是一个表中的不同文本类型。 我想将它们映射到在内部和映射中处理这些怪癖的类。

到目前为止我的解决方案:

隐藏的集合和虚拟对象,应该是只读的。对于加载,总是有效的Text对象,因为持久化内部集合会创建它们。

internal class Textline
{
    public virtual int Id { get; set; }

    public virtual TextType Type { get; set; }   // Enum

    public virtual int Linenumber { get; set; }
    public virtual string Text { get; set; }
}

public class Textmodule
{
    public virtual int Id { get; set; }

    public virtual string Key { get; set; }      // Unique
    public virtual TextType Type { get; set; }   // Enum

    protected internal virtual IList<Textline> Textlines { get; set; }
    public virtual string Text
    {
        get { Textlines.select(t => t.Text).Aggregate(/* ...*/); }
        set { /* split text to lines with max 80 chars and feed to Textlines*/}
    }
}

public TextmoduleMap()
{
    Table("textmodules");
    ReadOnly();    // problem: shouldnt insert and update at all, but does insert
    Where("linenumber = 1");  // starts with 1

    // doesnt matter because it shouldnt be saved
    Id(text => text.Id, "id").GeneratedBy.Custom<SimpleGenerator>();

    Map(text => text.Key);
    HasMany(text => text.Textzeilen)
        .Table("textmodules")
        .PropertyRef("Key")
        .KeyColumn("key")
        .Component(c =>
        {
            c.Map(line => line.Text)
                .Columns.Add("content", "length")
                .CustomType<StringWithLengthUserType>();
            c.Map(line => line.Linenumber, "linenumber");
        })
        .Cascade.AllDeleteOrphan()
        .Not.LazyLoad();
        ;
}

我的问题是,Readonly不会阻止nhibernate在保存时插入它。我能做些什么才能让它发挥作用,或者有人对更理智的域对象有更好的想法吗?

Edit2:我摆弄SQLInsert("SELECT 1");,但我得到异常“意外的行数-1,期望1”

感谢您的时间

1 个答案:

答案 0 :(得分:0)

我找到了一种相当难看的方式,可能不是很便携

public TextmoduleMap()
{
    ...
    ReadOnly();
    SqlInsert("DROP TABLE IF EXISTS temp; CREATE TEMP TABLE temp(id int); INSERT INTO temp (id) VALUES (1);");
    SqlDelete("DROP TABLE IF EXISTS temp; CREATE TEMP TABLE temp(id int); INSERT INTO temp (id) VALUES (1);");

    ...
}

仍然欢迎更好的方式