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 ?

2
  • 1
    1. Nope. 2. Nope. 3. Use context.Payments.Create<PaymentCheck>() Commented Jun 25, 2014 at 4:40
  • 1
    You might find this interesting. stackoverflow.com/a/16811976/150342 Commented Jun 25, 2014 at 9:05

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

It's not because of one liner. it's because of updating massive old code using default constructor.
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.
went down the refactor route... added a new Question to the matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.