Jeroen Huinink
Jeroen Huinink

Reputation: 2017

Linq-to-entities: How to create objects (new Xyz() vs CreateXyz())?

What is the best way of adding a new object in the entity framework. The designer adds all these create methods, but to me it makes more sense to call new on an object. The generated CreateCustomer method e.g. could be called like this:

Customer c = context.CreateCustomer(System.Guid.NewGuid(), "Name"));
context.AddToCustomer(c);

where to me it would make more sense to do:

Customer c = new Customer {
    Id = System.Guid.NewGuid(),
    Name = "Name"
};
context.AddToCustomer(c);

The latter is much more explicit since the properties that are being set at construction are named. I assume that the designer adds the create methods on purpose. Why should I use those?

Upvotes: 3

Views: 1714

Answers (3)

I guess it has to do with many things. It looks like factory method to me, therefore allowing one point of extension. 2ndly having all this in your constructor is not really best practice, especially when doing a lot of stuff at initialisation. Yes, your question seems reasonable, i even agree with it, however, in terms of object design, it is more practical as they did it.

Regards, Marius C. ([email protected])

Upvotes: 0

Craig Stuntz
Craig Stuntz

Reputation: 126557

As Andrew says (up-voted), it's quite acceptable to use regular constructors. As for why the "Create" methods exist, I believe the intention is to make explicit which properties are required. If you use such methods, you can be assured that you have not forgotten to set any property which will throw an exception when you SaveChanges. However, the code generator for the Entity Framework doesn't quite get this right; it includes server-generated auto increment properties, as well. These are technically "required", but you don't need to specify them.

Upvotes: 5

Andrew Peters
Andrew Peters

Reputation: 11333

You can absolutely use the second, more natural way. I'm not even sure of why the first way exists at all.

Upvotes: 2

Related Questions