Entity Framework 6 Create() vs new

随声附和 提交于 2019-12-06 17:37:43

问题


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!


回答1:


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




回答2:


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.




回答3:


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.




回答4:


If you use entity inheritance, you can achieve nice polymorphism behaviour using Create() method because it always instantiate correct Entity (not generic one). Example:

public DbSet GetDialDbSet(DialEnum type)
    {
        DbSet ret;
        switch (type)
        {
            default:
            case DialEnum.MAPPING_REASON:
                ret = DialMappingReasons; 
                break;

            case DialEnum.PROCESSING_INFORMATION:
                ret = DialProcessingInformation;
                break;
        }
        return ret;
    }

and polymorphism usage:

 DialDerived entity = (DialDerived) Db.GetDialDbSet(type).Create()


来源:https://stackoverflow.com/questions/31405958/entity-framework-6-create-vs-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!