This project is read-only.

Trouble adding first element to MList<>

Oct 2, 2010 at 8: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)






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.

Oct 3, 2010 at 12:42 AM

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


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.



Oct 5, 2010 at 12:18 AM

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