In an Application it has Data Access layer.In which it has DataEntityModel.edmx (entityframework model) and repository class.
Below code is my repository class.
namespace DataModel.Repository
{
public class ProductRepository
{
internal WebApiDbEntities Context;
internal DbSet<Product> DbSet;
public ProductRepository(WebApiDbEntities context)
{
this.Context = context;
this.DbSet = context.Set<Product>();
}
public virtual void Insert(Product entity)
{
DbSet.Add(entity);
}
}
}
Question is I have used DbSet.Add(entity) method to insert . But Entity Framework will generate it's own Add method Context.Products.Add(entity)
So, What is the difference between those two methods. Why Most of the time DbSet.Add(entity) is used ??
A repository replaces the use of the DbContext.
So to add an entity, instead of:
var dbContext = new WebApiDataModel();
dbContext.Products.Add(entity)
You use a repository:
var dbContext = new WebApiDataModel();
var productRepository = new ProductRepository(dbContext);
productRepository.Insert(entity);
In the end, both call DbSet<Product>.Add()
, but there are reasons why you may want to introduce the repository pattern with Entity Framework.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.