nhibernate mapping many rows to one object
i have a rather difficult mapping problem.
EDIT: reformulated descritpion
for historical reasons texts are not stored in a column as text, instead they are saved in tables. i have several tables with following structure:
TABLE SomeEntityTexts
(
id serial NOT NULL,开发者_如何学Go
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 is saved as lines with arbitrary length, different für each entity and sometimes even for different texttypes in one table. i would like to map them to classes which handle these quirks inside and in mappings.
my solution so far:
a hidden collection and a dummy object which should be readonly. For loading there are always valid Text-objects because persisting the inner collection creates them.
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();
;
}
My problem is, that Readonly doesnt prevent nhibernate from inserting it on save. Is there anything i can do to get it work or does someone has a better idea for a more sane domain object?
Edit2: I fiddled with SQLInsert("SELECT 1");
but i get exception "unexpected rowcount -1, expect 1"
thanks for your time
i found a rather ugly way which is probably not very portable
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);");
...
}
Better ways are still welcome
精彩评论