Hi,
For all my applications (ASP.NET MVC3, EF Code First), I have this general pattern that i'm using:
Entity:
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
EFDbContext:
public class EFDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.HasKey(p => p.ProductID)
.Property(p => p.ProductID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
I have a Generic Repository, which will be used by my Unit Of Work class, as below:
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly EFDbContext context;
private IGenericRepository<Product> _productRepository;
public UnitOfWork()
{
context = new EFDbContext();
}
public EFDbContext Context
{
get
{
return context;
}
}
public IGenericRepository<Product> ProductRepository
{
get
{
if (_productRepository == null)
{
_productRepository = new
GenericRepository<Product>(context);
}
return _productRepository;
}
}
I have a Service Layer, which as it should, models business logic. This layer, uses Unit Of Work, as below:
public class ProductService : IProductService
{
private IUnitOfWork unitOfWork;
public ProductService(IUnitOfWork unitOfWorkParam)
{
unitOfWork = unitOfWorkParam;
}
public void AddProduct(Product product)
{
unitOfWork.ProductRepository.Insert(product);
unitOfWork.Save();
}
}
Now, my UI project (ASP.NET MVC3), uses the service layer as below
public class HomeController : Controller
{
private IProductService productService;
public HomeController(IProductService productServiceParam)
{
productService = productServiceParam;
}
public ActionResult Products()
{
}
}
Thus the whole setup of the Projects to summazie would be:
Controller --> Service Layer --> UnitOfWork (which contains context, repositories)
--> DB
Now, my question is, the EFDbContext is contained in UnitOfWork, and thus, in this class, we can use queries such as:
using (var context = new EFDbContext())
{
}
but, how can i get this functionality migrated to my Service Layer, which uses UnitOfWork.Repositories ?
Have i missed something in design?
It would be great to have the Service Layer capable somehow of using the bare context object, where in we can use useful extension methods such as context.Entry<> ..
Can anyone please help me with this?
thanks.