在 EF7 中使用什么代替 DbSet Create() 方法,建议简单地使用 new T()

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

我在 ef 5 应用程序中使用 generic repository 模式。 在 IDbSet 中有一个 create() 方法,在 ef7 的 DbSet 中不存在。

EF5中Create()方法的说明如下:

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.

代码示例:

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();
    }
}

我的问题是,为什么 Create(); 方法在 EF7 的 DbSet 中被删除(注意 IDbSet 也在 EF 核心中被删除)

我发现了这个问题:Create() Versus new T(),如果我使用 new T() 以后会有什么问题吗?

我发现,之所以没有实施此类方法,是因为 Entity Framework Core (EF7) 根本不使用代理。因此,此类方法(为实体创建代理)的附加值消失了。在我看来,实体的默认构造函数是可行的方法。

查看讨论:https://github.com/aspnet/EntityFramework/issues/3797

Microsoft.EntityFrameworkCore.Proxies NuGet 包现在为 EF Core 实体提供代理。这些代理 support lazy loading from version 2.1, and more efficient change tracking(与 POCO 相比)自版本 5.0.

名称已从 DbSet<T>.Create() 更改为 DbSet<T>.CreateProxy() 以更清楚地表明其唯一目的是创建代理。如果您不需要代理 class,那么 new T() 确实是正确的方法。

请注意,您必须 opt in to the proxy features 要使用,例如UseChangeTrackingProxies and/or UseLazyLoadingProxies,创建 DbContext 时。