ahmad molaie
ahmad molaie

Reputation: 1540

What to use instead of DbSet Create() Method in EF7, and is it recommended to simply new T()

I am using generic repository pattren in an ef 5 app. there is a create() method in IDbSet, which in ef7's DbSet does not exists.

description of Create() Method in EF5 is as follow:

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. The instance returned will be a proxy if the underlying context is configured to create proxies and the entity type meets the requirements for creating a proxy.

Code sample:

public interface IRepository<T> where T : IDisposable {
    T Create();
}

public class Repository<T> : IRepository<T> where T :  IDisposable {

    protected IUnitOfWork uow;
    protected IDbSet<T> entity;

    public Repository(IUnitOfWork uow) {
        this.uow = uow;
        this.entity = uow.Set<T>();
    }

    public T Create() {
        return entity.Create();
    }
}

my question is, why Create(); method is removed in EF7's DbSet(notice that IDbSet is also removed in EF core)

and I Found this question: Create() Versus new T(), have i any problem in future if i use new T()?

Upvotes: 11

Views: 5354

Answers (2)

Tobias J
Tobias J

Reputation: 22883

The Microsoft.EntityFrameworkCore.Proxies NuGet package now provides proxies for EF Core entities. These proxies support lazy loading from version 2.1, and more efficient change tracking (when compared to POCOs) since version 5.0.

The name was changed from DbSet<T>.Create() to DbSet<T>.CreateProxy() to make it more clear that its only purpose is to create a proxy. If you don't need a proxy class, then just new T() is indeed the correct approach.

Note that you must opt in to the proxy features you want to use, e.g. UseChangeTrackingProxies and/or UseLazyLoadingProxies, when creating the DbContext.

Upvotes: 8

Martijn van Put
Martijn van Put

Reputation: 3313

What i found is that the reason why such methods are not implemented is that Entity Framework Core (EF7) doesn't use proxies at all. So the added value for such methods (which creates a proxy for an entity) are gone. In my opinion the default constructor of an entity is the way to go.

See the discussion: https://github.com/aspnet/EntityFramework/issues/3797

Upvotes: 6

Related Questions