I just want to know now how to separate code in proper way in MVC3 using EF
As per my project structure.
Presentation -> View & Controller
Domain –> Model (Business Entity)
Data –> RepositoryBase, IRepository, ApplicationDbContext
Services –> 3rd Party Service (PayPal, SMS) or Application Service
ApplicationDbContext require Model as reference.
public sealed class ApplicationDbContext : DbContext
{
public DbSet<CountryModel> Country { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
1. So is it good to place DbContext in Data ? Or I have to move it into Domain ?
Now in Controller I have to write a code
using (ApplicationDbContext db = new ApplicationDbContext())
{
var countryRepository = new Repository<Country>(db);
if (ModelState.IsValid)
{
countryRepository.insert(country);
db.SaveChanges();
}
}
Is there any way to Separate this code block any Business Layer / Service Layer ?
So we just Call that Layer from controller & just pass the Specific Business Entity in order to perform rest of the operation.
I want to do PL –> BLL –> DLL approach Using MVC 3 & EF ?
Please suggest me the proper way.
Yes, it’s where it belongs.
No, you absolutely should not write code like this in the controller because you are now making your controller strongly coupled to the specific data access technology you are using (EF in your case). Even worse you will not be able to unit test your controllers in isolation.
I would recommend you abstracting the operations over the entities in an interface (you already have mentioned it by the way in your question –
IRepository). And now your controller could take the repository as dependency:Now all you have to do is configure your favorite dependency injection framework to inject the specific implementation of this IRepository into the controller constructor. In your case this specific implementation could be some class that implements the IRepository interface and which is using the
ApplicationDbContextinside.This way you are abstracting away the data access logic from your controllers.