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

c# entity-framework entity-framework-core

Question

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()?

1
7
5/23/2017 12:13:40 PM

Accepted Answer

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

4
4/29/2016 6:13:23 PM

Popular Answer

Now that EF Core supports proxies and lazy loading, there is a DbSet.CreateProxy() extension method. It looks like they changed the name to make it more clear that its only purpose is to create a proxy.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow