我有以下代码:
// setup
var sessionFactory = SessionManager.CreateSessionFactory(true);
// business
using (var session = sessionFactory.OpenSession())
{
using (var tran = session.BeginTransaction())
{
var user1 = new UserDto() {Email = "e1@ma.il", FirstName = "FN1", LastName = "LN1"};
var user2 = new UserDto() {Email = "e2@ma.il", FirstName = "FN2", LastName = "LN2"};
var projType1 = new ProjectTypeDto() {ProjectTypeName = "ptn1", ProjectTypeDescription = "ptd1"};
var timeSheet1 = new TimeSheetDto(){ Comment = "c1", User = user1, ProjectType = projType1 };
var timeSheet2 = new TimeSheetDto(){ Comment = "c2", User = user2, ProjectType = projType1 };
session.SaveOrUpdate(timeSheet1);
session.SaveOrUpdate(timeSheet2);
tran.Commit();
}
}
打破了“tran.Commit();”线。
Exception表示timeSheet引用NotExistent用户。 (很明显)
如何自动添加所有相关对象?
我正在使用以下映射:
public class TimeSheetMap : ClassMap<TimeSheetDto>
{
public TimeSheetMap()
{
Id(x => x.Id);
Map(x => x.StartTime);
Map(x => x.EndTime);
Map(x => x.Comment);
References(x => x.User).Cascade.All();
References(x => x.ProjectType).Cascade.All();
}
}
答案 0 :(得分:1)
您需要使用inverse将一侧声明为父级,否则保存双方。尝试将时间表地图链接到:
public class TimeSheetMap : ClassMap<TimeSheetDto>
{
public TimeSheetMap()
{
Id(x => x.Id);
Map(x => x.StartTime);
Map(x => x.EndTime);
Map(x => x.Comment);
References(x => x.User).Cascade.All().Inverse();
References(x => x.ProjectType).Cascade.All().Inverse();
}
}