Bart Calixto
Bart Calixto

Reputation: 19705

context.Entities.Create() with default constructor

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 ?

Upvotes: 0

Views: 150

Answers (1)

Kirill Shlenskiy
Kirill Shlenskiy

Reputation: 9587

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

Upvotes: 1

Related Questions