Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 Create() vs new

What is the difference between adding an entity in these two ways?

MyEntity me = new MyEntity();
entities.myentities.Add(me);

vs

MyEntity me = entities.myentities.Create();

Do I still need to add "me" in the second example? If so, is there some sort of advantage, one way or the other?

Many thanks!

like image 549
Yabbie Avatar asked Jul 14 '15 11:07

Yabbie


3 Answers

MyEntity me = new MyEntity();

will create a new instance of MyEntity

MyEntity me = entities.myentities.Create();

will create a proxy wrapped instance of MyEntity (assuming your context is configured to create proxies)

This proxy overrides some virtual properties of the entity to insert hooks for performing actions automatically when the property is accessed. For example, this mechanism is used to support lazy loading of relationships.

from here

like image 115
qujck Avatar answered Oct 03 '22 01:10

qujck


Yes, you still need to add it. From the documentation of the Create method:

Creates a new instance of an entity for the type of this set. Note that this instance is NOT added or attached to the set.

like image 40
Glorfindel Avatar answered Oct 03 '22 03:10

Glorfindel


MyEntity me = new MyEntity();

is equal to

MyEntity me = entities.myentities.Create();

Both of the above create a new instance of MyEntity but neither attach it to the DbSet represented by myentities.

The line

entities.myentities.Add(me)

attaches the instance to the DbSet, though you could use Attach(me) as well.

The "me" is required in the second example as you would be creating an instance of object without a reference to hold the object.

like image 39
John Davidson Avatar answered Oct 03 '22 01:10

John Davidson