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()?
DbSet in Entity Framework 6. The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext) must include the DbSet type properties for the entities which map to database tables and views.
The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext) must include the DbSet type properties for the entities which map to database tables and views.
The following table lists important methods of the DbSet class: Adds the given entity to the context with the Added state. When the changes are saved, the entities in the Added states are inserted into the database. After the changes are saved, the object state changes to Unchanged.
Creating entity with DbSet.Create () In order to be able create new entities as proper dynamic proxies the DbSet class provides Create method. This method returns new dynamic proxy instance which isn't added or attached to the context. To use it only a single line of code needs to be changed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With