Entity Framework Create Entity<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Entity Framework Create Entity

Posted on: July 15, 2014

Creating a new instance and having Entity Framework handling this one in its context require some manipulations. You have two different paths to accomplish this goal. The first one is to create the entity and to add them to the DbSet. The second one is to create the instance from the DbSet directly instead of instantiated this one with new keyword. Here is a code that add two entities. One that is not tracked by Entity Framework and when that it is because it has been created with the Create method.

1using (var context = new YourContext()) {
2 // Create a new instance with Add
3 var person = new Person {Name = "New person with New Keyword",BirthDate = DateTime.Now};
4 Console.WriteLine("Person non-proxy state: " + context.Entry(person).State);
5 context.Persons.Add(person);// Now Entity Framework added the object but was not tracking anything
7 // Create a new instance with Entity Framework (proxy)
8 var person2 = context.Persons.Create();
9 Console.WriteLine("Person proxy state: " + context.Entry(person2).State);
10 person2.Name = "New Person from EF";
11 person2.BirthDate = DateTime.Now;
12 context.Persons.Add(person2); // Still need to add but EF was tracking changes
13 var x1 = context.Persons.Local.Count();
14 Console.WriteLine("The count is at " + x1);
16 // Detect Changes
17 context.ChangeTracker.DetectChanges();
18 Console.WriteLine("Person non-proxy state: " + context.Entry(person).State);
19 Console.WriteLine("Person proxy state: " + context.Entry(person2).State);
20 var x2 = context.Persons.Local.Count();
21 Console.WriteLine("The count is at " + x2);
23 context.SaveChanges();

The result is the same for those two creations because we do not use anything from the Entity Framework Proxy. Choosing from one or the other method to create is more a preference than a guidance. You have to choose which one you prefer and keep your whole system using the same. Otherwise, it will be confusing to know if we need to or not bound the entity to EF proxies.


You can get the source code on GitHub or download the Zip file.