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