我有一个一对多的映射。具有集合的实体持久存在于两个表 1:N
这是类和映射:
public class Test
{
public virtual string Id { get; set; }
public virtual string Description { get; set; }
public virtual IList<TestItem> Items { get; set; }
public Test()
{
Items = new List<TestItem>();
}
}
public class TestItem
{
public virtual string Id { get; set; }
public virtual Test Test { get; set; }
public virtual string ItemCode { get; set; }
public virtual string ItemData { get; set; }
}
public class TestMap : ClassMapping<Test>
{
public TestMap()
{
Id(x => x.Id, m => m.Column("IDTest"));
Bag(x => x.Items, c =>
{
c.Key(k =>
{
k.NotNullable(true);
k.Column("IDTest");
});
c.Cascade(Cascade.DeleteOrphans);
c.Lazy(CollectionLazy.NoLazy);
c.Inverse(true);
}, r => r.OneToMany(m =>
{
m.NotFound(NotFoundMode.Exception);
m.Class(typeof(TestItem));
}));
}
}
public class TestItemMap : ClassMapping<TestItem>
{
public TestItemMap()
{
Id(x => x.Id, m => m.Column("IDTestItem"));
ManyToOne(x => x.Test, m =>
{
m.Column("IDTest");
m.NotNullable(false);
m.Lazy(LazyRelation.NoLazy);
});
Property(x => x.ItemCode);
Property(x => x.ItemData);
}
}
这就是代码。如果我删除标记的行,我会收到错误消息。
var session = SessionFactory.OpenSession();
using (var tr = session.BeginTransaction())
{
var test = new Test();
test.Id = "T01";
test.Description = "Desc TEST 01";
session.SaveOrUpdate(test); // If Removed Get INSERT ERROR on TestItem
var item = new TestItem { Id = "NEW01", ItemCode = "A", Test = test, ItemData = "New T01A" };
test.Items.Add(item);
session.SaveOrUpdate(item);
session.SaveOrUpdate(test);
tr.Commit();
}
我的问题是:
这是保持“一对多”关系的最佳做法吗?
可以使用下面的代码并全部保存,只保存标题行(测试)并自动级联子表上的所有插入?
var session = SessionFactory.OpenSession();
using (var tr = session.BeginTransaction())
{
var test = new Test();
test.Id = "T01";
test.Description = "Desc TEST 01";
//session.SaveOrUpdate(test); // If Removed Get INSERT ERROR on TestItem
var item = new TestItem { Id = "NEW01", ItemCode = "A", Test = test, ItemData = "New T01A" };
test.Items.Add(item);
//session.SaveOrUpdate(item);
session.SaveOrUpdate(test);
tr.Commit();
}
我想我需要在我的映射代码上进行一些更改,但我不明白是什么!!!
许多天的工作,谷歌搜索,stackoverflow,但没有任何改变结果。
谢谢!!!