Recursive save doesn't work

Posts   
 
    
Posts: 9
Joined: 06-Sep-2012
# Posted on: 18-Feb-2013 17:24:25   

I have two tables that look like this:

Customer ID int (PK) NOT NULL Name varchar(250) NOT NULL

Order ID int (PK) NOT NULL Name varchar(250) NOT NULL CustomerID int (FK to Customer.ID) NOT NULL

If I try to save an entity recursivly, I get an SQL exception that says that the CustomerID of Order is not set.

var customerEntity = new CustomerEntity();
customerEntity.Name = "Test";
customerEntity.Orders.Add(new OrderEntity { Number = "Test" });

using (var adapter = new DataAccessAdapter())
{
    adapter.SaveEntity(customerEntity, true, true);
}

Why doesn't LLBLGen set the foreignkey field with the id of the saved Customer entity automatically? Do I have to do that manually?

I'm using LLBLGen 3.5 and SQL Server.

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 18-Feb-2013 19:06:10   

You don't set any fields on the Customer, so the framework skips it. And since it was not inserted, there was no PK fetched back to be used in inserting the Order.

Posts: 9
Joined: 06-Sep-2012
# Posted on: 18-Feb-2013 20:21:25   

Walaa wrote:

You don't set any fields on the Customer, so the framework skips it. And since it was not inserted, there was no PK fetched back to be used in inserting the Order.

Sorry, my example wasn't complete. I updated my first post.

I found out what causes my problem. I removed the navigator field "Customer" from Order, because I didn't want to have the relation visible on the OrderEntity.

Do I really need the navigator field?

If I remember rightly it was possible in LLBLGen v2.6 to hide a relation on one side (Order) and still be able to save it recursively.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 19-Feb-2013 06:11:00   

It's recommended to have the navigator on both sides, because of PK/FK sync (ref...).

In your example when you do customer.Orders.Add(...), the sync code can't find any order's property to sync with, so it just add the order to the customer.

If you want to hide the navigator for some reason, it's recommended to turn off the "Navigator property is public" setting:

  1. At LLBLGen Designer go and edit the Order Entity.
  2. Go to "Code gen. info" sub-tab.
  3. At the 'element' comboBox, select the Customer navigator.
  4. Turn off the "Navigator property is public" setting
  5. Re-generate the code. Now the navigator is an internal property, so the developers can't access it, but still you have pk/fk sync.
David Elizondo | LLBLGen Support Team
Posts: 9
Joined: 06-Sep-2012
# Posted on: 19-Feb-2013 09:14:49   

Thanks, this is what I was looking for!