Ramifications of DbSet.Create versus new Entity()

Entity FrameworkEntity Framework-4.1

Entity Framework Problem Overview


I am a bit confused about whether to use DbSet.Create, or simply new up an entity and add it. I don't really understand the ramifications of using DbSet.Create.

I understand that DbSet.Create will create a proxied version if applicable, but I don't really understand what that means. Why do I care? It seems to me that an empty Proxied class is no more useful than a non-proxied class, since there are no related entities to lazy load.

Can you tell me the difference, beyond the obvious? And why would you care?

Entity Framework Solutions


Solution 1 - Entity Framework

A scenario where using DbSet<T>.Create() makes sense is attaching an existing entity to the context and then leverage lazy loading of related entities. 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; }
}

The following would work then:

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;
        // ...
    }
}

Here lazy loading of children is triggered (perhaps with resulting empty collection, but not null). If you'd replace context.Parents.Create() by new Parent() the foreach loop will crash because parent.Children is always null.

Edit

Another example was here (populating a foreign key property of a new entity and then getting the navigation property lazily loaded after the new entity is inserted into the DB): https://stackoverflow.com/q/6312981/270591

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErik FunkenbuschView Question on Stackoverflow
Solution 1 - Entity FrameworkSlaumaView Answer on Stackoverflow