Reputation: 10713
I use Entity Framework in my C# projects for a database connection.
Let's say I have a table on my database which has 3 columns: table: Car columns: id, color, type, numberOfDoors
Here is how I create a new record for this table:
Car c = new Car();//default constructor
c.color = "blue";
c.type = "Opel";
c.numberOfDoors = 2;
myDatabase.tblCar.AddObject(c);
myDatabase.SaveChanges();
I'm doing this in a lot of places in my project, so the first 4 lines are repeated a lot. So I was thinking, why doesn't Entity Framework have a constructors with parameters? I thought that maybe the columns which can be null in db can be the reason for this.
Upvotes: 0
Views: 57
Reputation: 2652
EF generates static constructor CreateX methods for each Entity (class) it generates. For example, on one of my User classes I can do the following:
User user = User.CreateUser(userID, password, email, userTypeId);
This does most of what you would want in terms of quickly setting up a new instance of an entity class. Of course this does NOT add the new instance to the collection or save changes; you might want to create 50,000 instances and saving every time would be wasteful.
Upvotes: 1
Reputation: 190942
Entity Framework is trying to be as general as possible. Plus some models might have 10+ properties off of them. That would be quite messy if you only needed to assign a small subset of them. Another reason is that it would be messy to construct the models inside of Entity Framework.
The classes are generated with the partial
keyword and you should be able to add it yourself.
Upvotes: 1