Ruslan
Ruslan

Reputation: 3028

FluentNHibernate - cascade inserting

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 = "[email protected]", FirstName = "FN1", LastName = "LN1"};
      var user2 = new UserDto() {Email = "[email protected]", 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();
    }
  }

Upvotes: 0

Views: 2359

Answers (1)

Fourth
Fourth

Reputation: 9351

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

Upvotes: 1

Related Questions