I thought I would write a short post with a very specific title in the hopes that it can serve as a beacon, a shining light for fellow ‘idiots’ who are wasting time on a relatively simple, yet mostly undocumented matter.
Last Thursday I had a relatively simple task to do. I needed to instantiate a new POCO object from a context, set a couple of values, then save it. This entity has a bunch of properties – but most of them should have defaults. And I want it to save the defaults.
So I figure, simple enough. I go into my edmx and add default values to the columns I wish to have default values. I save this, then go into my POCO T4 template and regenerate it so it reflects the changes in the edmx.
I think to myself ‘Great, that should be it! Now when I call CreateObject<MyObjectType> to grab a proxy-wrapped instance of the POCO I just set the defaults on, the entity framework will populate the properties I set the defaults on with the values I specified!’
I run the app, and lo and behold, my object has nulls for all it’s properties. Great. And no, there is no magic population that occurs when you try to call SaveChanges() on the context you created it from either (Another far fetched theory that went through my head).
So the answer is quite simple – although we all know that means sometimes we just miss it. Just make sure you re-save your POCO Entity text template! If you look at the T4 code - the template feeds off the default values specified in the POCO context, and inserts the default values directly into your objects. This is fairly simple, my only issue was is I couldn’t find a single resource to tell me this is what occurs!
Here is a small snapshot of what your POCO will look like with some defaults:
Code Snippet
- namespace Planet.Sonia.SoniaModel.POCOEntities
- {
- public partial class Contact
- {
- #region Primitive Properties
-
- public virtual int ContactId
- {
- get;
- set;
- }
-
- public virtual string Salutation
- {
- get { return _salutation; }
- set { _salutation = value; }
- }
- private string _salutation = "";
-
- public virtual string FirstName
- {
- get { return _firstName; }
- set { _firstName = value; }
- }
- private string _firstName = "";
-
- public virtual string MiddleName
- {
- get { return _middleName; }
- set { _middleName = value; }
- }
- private string _middleName = "";
-
- public virtual string LastName
- {
- get { return _lastName; }
- set { _lastName = value; }
- }
- private string _lastName = "";
Hopefully this helps a few others out.
Print | posted on Monday, 30 August 2010 9:26 AM