0

I have the following code:

  // 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();
    }
  }

It breaks on the "tran.Commit();" line.

Exception says that timeSheet refers to NotExistent users. ( it's obvious )

How to make it autoamtically add all related objects?

I'm using the following mapping:

  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();
    }
  }
Ruslan
  • 2,678
  • 3
  • 22
  • 25
  • It should work, show a UserDto class map, why you don't use session.Save(timeSheet1);? I think the problem can by with Inverse, but I'm waiting for your class map – Adam Łepkowski Apr 14 '12 at 20:45

1 Answers1

1

You need to declare one side to be the parent using inverse, otherwise save both sides. Try chaning your timesheet map to:

  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();
    }
  }
Fourth
  • 9,163
  • 1
  • 23
  • 28