DbSet.Create ramifications against new object ()

I'm a little confused about whether to use DbSet.Create or just create a new entity and add it. I really don't understand the implications of using DbSet.Create.

I understand that DbSet.Create will create a proxied version if applicable, but I really don't understand what that means. Why does it bother me? It seems to me that the empty Proxied class is no more useful than the non-proxied class, since there are no related objects for lazy loading.

Can you tell me the difference, beyond the obvious? And why does it bother you?

+49
entity-framework
Sep 05 '11 at 19:15
source share
1 answer

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; // assuming it exists in the DB context.Parents.Attach(parent); foreach (var child in parent.Children) { var name = child.Name; // ... } } 

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

+51
Sep 05 '11 at 19:57
source share



All Articles