Ramifications of DbSet.Create versus new Entity()
Asked Answered
G

1

53

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?

Guertin answered 5/9, 2011 at 19:15 Comment(0)
R
55

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): Lazy loading properties after an insert

Reynolds answered 5/9, 2011 at 19:57 Comment(2)
Ahh.. I didn't realize that you could just populate a foreign key id and have it lazy load it without all the fuss. I guess I can see how that might be useful if you don't want to load the existing record and just want the child.Guertin
What to do if "context.Parents" is null, i am trying your case and it seems it is workable but unfortunately for me "context.Parents" is null so here exception generates like An exception of type 'System.NullReferenceException' occurred in YourProject.dll but was not handled in user code Additional information: Object reference not set to an instance of an object. If do you have any solution please let me know, so i will overcome and will write in my notes for escaping it from next occurrences.Re

© 2022 - 2024 — McMap. All rights reserved.