A scenario in which using DbSet<T>.Create() makes sense is to attach an existing object to the context and then use lazy loading of related objects. Example:
public class Parent { public int Id { get; set; } public virtual ICollection<Child> Children { get; set; } } public class Child { public int Id { get; set; } public string Name { get; set; } }
Next, the following will work:
using (var context = new MyDbContext()) { var parent = context.Parents.Create(); parent.Id = 1;
This starts the lazy loading of children (possibly as a result of an empty collection, but not null ). If you replace context.Parents.Create() with new Parent() , the foreach loop will fail because parent.Children always null .
Edit
Another example was here (filling in a foreign key property for a new object, and then getting the navigation property loaded lazily after the new object is inserted into the database): Lazy load properties after insertion
Slauma Sep 05 '11 at 19:57 2011-09-05 19:57
source share