Project: MvcDataEntry
[The "big picture" of the project has to come]The Data Layer is implemented using EntityFramework, but really the application doesn't know the ORM behind:
internal class ShopDbContext :
EntityFrameworkUnitOfWork,
IShopDbContext,
IShopDb
{
public ShopDbContext(string connectionName)
: base(connectionName)
{
}
public ShopDbContext(ConnectionStringSettings connectionSettings)
: base(connectionSettings)
{
}
public ShopDbContext(string providerName, string connectionString)
: base(providerName, connectionString)
{
}
public IRepository<Customer> CustomerRepository
{
get
{
return Repository<Customer>();
}
}
public bool Exists()
{
return Database.Exists();
}
public void Create()
{
Database.Create();
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Customer>();
}
}
The MVC controller uses the UnitOfWork interface:
public class CustomerController : Controller
{
private readonly IShopDbContext context;
public CustomerController(IShopDbContext context)
{
this.context = context;
}
[HttpGet]
public ActionResult List()
{
Mapper.CreateMap<Customer, CustomerModel>();
using (context)
{
var customerList =
context
.CustomerRepository
.ToList()
.Select(Mapper.Map<Customer, CustomerModel>);
return Render("List", new CustomerListModel(customerList));
}
}
[HttpPost]
public ActionResult Edit(Guid id)
{
using (context)
{
var customer =
context
.CustomerRepository
.Single(c => c.Id == id);
return Render("Edit", Mapper.Map<Customer, CustomerModel>(customer));
}
}
[HttpPost]
public ActionResult Save(CustomerModel customerModel)
{
Mapper.CreateMap<CustomerModel, Customer>();
using (context)
{
context.CustomerRepository.Update(Mapper.Map<CustomerModel, Customer>(customerModel));
context.Commit();
return Render("Saved");
}
}
private ActionResult Render(string viewName, object model = null)
{
if (Request.IsAjaxRequest())
{
return
model == null ?
PartialView(viewName) : PartialView(viewName, model);
}
return
model == null ?
View(viewName) : View(viewName, model);
}
}
At the end the MVC Razor view:
@model EyeOpen.Web.Mvc.Models.CustomerListModel
@{
const string UpdateTargetId = "async";
var options =
new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = UpdateTargetId,
InsertionMode = InsertionMode.Replace
};
}
<div id="customerList">
@using (Ajax.BeginForm(options))
{
<fieldset>
<legend>Customer list</legend>
<div>
@foreach (var customer in Model.CustomerList)
{
<span>@customer.Name</span>
@Ajax.ActionLink("Edit", "Edit", "Customer", new { id = @customer.Id }, options)
<br />
}
</div>
</fieldset>
}
</div>
<div id="@UpdateTargetId"></div>