POCO: CreateObject and object initializer

When we work with POCO entities, queries return instances of proxy class which inherits entity types. Having some proxy instances allow us to use lazy loading.


When we create an entity in order to attach it to the context, we can do a new on our entity type but it can be better to instanciate the proxy class. To do this, we can use CreateObject<T>() method on the context.


However, in this case, it’s a shame because we can’t use object initializers.


My idea is to make some methods on the context: CreateCategory, CreateProduct, etc. and to use their parameters to initialize my entities. To do this, I use optional parameters (new C#4 feature) to have something like Object Initializers.


Writing these methods can be boring.


So, I update my code generation template and, with it, these methods are automatically generated.


If you look at my template code, you’ll be able to see that I use another new C#4 feature: the variance. I use it to cast an IEnumerable<PrimitiveTypePropertyWrapper> to IEnumerable<DataPropertyWrapper>.


Now, I can write the following code:


context.CreateCategory(id:1, name:“C1″, description:“D1″);

This entry was posted in 10511, 7671, 7672, 7674, 7675. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>