0

Is it possible to use a constructor with EF entities?

I want to add a new instance of an Entity Framework entity and add it to a List<>

i.e.

List<MyObject> objectList = new List<MyObject>();
objectList.Add(new MyObject( "property" , 1);

instead of

List<MyObject> objectList = new List<MyObject>();
MyObject object = new MyObject();
object.Name = "property1";
object.ID = 1;
objectList.Add(object);
1
  • Do you understand that you're using constructors in both your samples? And while you can add parametrized constructors to Entity Framework entities, you may not need it to achieve code brevity you have in your first example. What and what for do you really need? Commented Aug 3, 2012 at 20:36

1 Answer 1

2

Yes, you can absolutely do that.

Entity Framework Code First is all about persistence ignorance. That is, you can write code the way you always have and the persistence part "just works". In reality there are a few limitations on that goal, but for the most part it works as advertised.

Note that there must be a parameterless constructor as well (so that Entity Framework can instantiate instances of the object automatically). But you can also have as many parameterized constructors as you want.

Sign up to request clarification or add additional context in comments.

Comments

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.