Trouble adding first element to MList<>

Oct 2, 2010 at 7:31 PM

I cannot seem to add an element to MList<>. Using the tutorial, I made the following changes:

To Customer, add this field:

           MList<String> children;

           public MList<String> Children

           {

               get { return children; }

               set { Set(ref children, value, "Children"); }

           }

Then try to add a customer like this:

           CustomerDN homer = new CustomerDN

           {

               Name = "Homer",

               SureName = "Simpson",

               Dob = DateTime.Today.AddYears(-40)

           };

 

           Database.Save<CustomerDN>(homer);

           homer.Children.Add("Bart");

           Database.Save<CustomerDN>(homer);

When I run this, the add bart command gives the following error message:

NullReferenceException was unhandled.

I guess that I am missing some piece needed to initialize the MList object. Can you help me to understand why I am getting this message?

I am using Visual Studio 2008 Express.

Coordinator
Oct 2, 2010 at 11:42 PM

Hi Hezak1ah,

One of the directives in the design of the engine is to keep type mismatch between SQL Tables and CLR entities as small as possible, so the types and nullability of fields is preserved by default, as well as the way the structure of the entities is mapped to tables.

There's however two exceptions to this rule:

* There's no difference between and MList field that is null, from one that has no elements.
* There's no difference between an string that is null, and an empty string.

So, whenever you RETRIEVE and entity with string or MList u will get empties, not nulls. In this case however u are SAVING, and this does not initialize the fields for you. 

On the other side, its your own decission to initialize the field or not. 

Pro Initialize: 
 * Simplified Adding element without testing the collection first.

Pro Not Initializing:
* Performance improvements when retriving an entity, cos the collection will be initialized twice.
* Performance improvements when filling an MList with a LINQ query, ore replacing the collection itself, for the same reason.

I usually don't initialize them in the class definition, the framework is quite prepared for it, EntityList will initialize if necessary for example, and at the end when the entity is new I usually fill the list with LINQ queries anyway. 

homer.Children = new []{"Bart", "Lista"}.ToMList(); 

In your example, however, it will make the code more dirty since u will have to do something like:

if(home.Children == null)
   home.Children = new MList<string>();

home.Children.Add("Bart");

So you can initialize in the field if u want :).

I could answer quicker, but i preffer that u knoe the pros and cons and u take the intelligent choice.

Cheers! 

 

Oct 4, 2010 at 11:18 PM

Thanks for a great answer. That helped me think through some bigger issues as well.