Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ramifications of DbSet.Create versus new Entity()

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?

like image 988
Erik Funkenbusch Avatar asked Sep 05 '11 19:09

Erik Funkenbusch


People also ask

What is the use of DbSet in Entity Framework?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext. Set method.

What is DbSet and entity set?

A DbSet represents an entity set. An entity set is defined as a set of entities of the same entity type. From the perspective of the database, it usually represents the table. Each Entity type must expose the DbSet Property to be able to participate in the CRUD Operations.

What is DbSet in Entity Framework Core?

In Entity Framework Core, the DbSet represents the set of entities. In a database, a group of similar entities is called an Entity Set. The DbSet enables the user to perform various operations like add, remove, update, etc. on the entity set.


1 Answers

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

like image 56
Slauma Avatar answered Sep 18 '22 09:09

Slauma