0

When using Entity Framework DbContext, to create a new entity and wrap it in a proxy class, one does :

var product = context.Products.Create();

that creates a proxy for the entity, but doesn't allow for contructor variable initialization like :

var product = new Product { name = "Product Name" };

Question 1 : Is there any way to create a proxy for an already instanciated object ? like :

context.Products.CreateProxyFrom(product) 

Question 2 : Is there any way to create the a class initialization like

context.Products.Create() { name = "Product Name" };

I know both option does not exist, I'm wondering is there some shortcut or workaround around this.


Question 3:

Having PaymentCheck : Payment (inheritance) I can only do context.Payments.Create(); but I need a PaymentCheck instance. how can I do a create of PaymentCheck ?

Bart Calixto
  • 19,210
  • 11
  • 78
  • 114

1 Answers1

1

I really don't see the big deal with just setting property values after the proxy has been created, but if you absolutely must have the property value setting on the same line and aren't afraid to pollute your IntelliSense a bit, you can always get a bit functional with extension methods:

public static T Apply<T>(this T input, Action<T> action)
{
    action(input);

    return input;
}

Usage:

Product product = context.Products.Create()
    .Apply(p => p.name = "Product Name")
    .Apply(p => p.category = 42);
Kirill Shlenskiy
  • 9,367
  • 27
  • 39
  • It's not because of one liner. it's because of updating massive old code using default constructor. – Bart Calixto Jun 25 '14 at 03:20
  • Then you're pretty much stuck with refactoring - unless you're ready to roll your own `CreateProxyFrom` extension method which will take in a concrete object instance, create a proxy and copy the property values using Reflection or AutoMapper-type tool while taking care not to touch navigational properties. It's dangerous and wasteful, but doable if you really can't afford to go down the refactoring route. – Kirill Shlenskiy Jun 25 '14 at 03:59
  • went down the refactor route... added a new Question to the matter. – Bart Calixto Jun 25 '14 at 04:29