EricM wrote:
I've been using LLBLGen Pro for a couple of months and have been thrilled at how much work it saves. However, I've come across an issue that I can't seem to figure out. It seems like it would be a pretty common issue but I haven't seen any other posts about it specifically so I assume I'm missing something.
I'm using the SelfServicing model and everything works like a dream except where I access a new related entity via the parent entity's property. For example, let's say I have 2 tables: A and B. Table A has the following columns: ID and Name, where ID is the PK. Table B has the following columns: ID and Phone, where ID is the PK and is a FK that references A.ID.
If my code is as follows:
AEntity a = new AEntity();
a.ID = 1;
a.Name = "John Doe";
a.Save(true);
a.B.Phone = "5551112222";
Console.WriteLine("Phone: {0}", a.B.Phone);
The resulting output is:
Phone:
The value in a.B.Phone is an empty string even though I just set it in the line right before.
No, you haven't
The problem is this: when you do: a.B.Phone, the lazy loading code tries to load B for the a instance, as you're touching the property. Because B doesn't exist, it returns a new entity and doesn't mark that new entity as being 'loaded', as it didn't exist. So when you re-touch a.B, it will retry to load the entity, which again fails.
To work around this, do:
a.B = new BEntity();
and now you can set the properties without problem, as a.B is indeed set to an existing value:
a.B.Phone="5551112222";
It's kind of awkward, I admit, but the lazy loader code's first priority is to deliver related entities IF available. As you haven't set a.B to a value, the code assumes the related BEntity has to be read from the DB and will re-try until it has read one OR you've set a.B to a value.
Obviously, this is an oversimplified example, but it illustrates the issue. The problem is also apparent if I were to have multiple properties in BEntity and were to try to set multiple properties before saving a.B.
If there is no related BEntity for a, then you can only save a.B if you set it explicitly to a new value, i.e. new BEntity(); as I did in the line which solves your problem
That a.B returns a new entity is not helping, I admit, however that was done to avoid errors in value-read code in forms for example.