Reputation: 279
I have a Database with the following Tables
I modeled these in EF using inheritance.
I created the controller with the Controller creation wizard in VS2010 using the Base Entity (Businesses)
I want to re-use the same Create action for all three types.
[HttpPost]
public ActionResult CreateHotel(Business business)
{
if (ModelState.IsValid)
{
db.Businesses.AddObject(business);
db.SaveChanges();
return RedirectToAction("Index");
}
If i modify the function as shown bellow it does correctly create a Business of type Hotel
public ActionResult CreateHotel(Hotels business)
So the question is how can i do this dynamically. Is there a better way to do this?
Upvotes: 2
Views: 155
Reputation: 1962
Couple of ways to achieve it. However, automatically generated model will not help.
Leverage classic builder design pattern. Define a viewmodel, which can capture data for all three models, Hotels, Restaraunts, Airports. In the view model keep a distinguisher like "BusinessType" etc. and a function to create the appropriate business object by looking at type. The distinguisher needs to be set up in UI statically or dynamically.
public class BusinessViewModel
{
// all attributes go here.
public int BusinessType { get; set; }
public Businesses CreateBusinessObject()
{
if(BusinessType == "1")
//Create and return a new Hotel
}
}
In the controller it will be used like this :
[HttpPost]
public ActionResult CreateHotel(BusinessViewModel businessVM)
{
if (ModelState.IsValid)
{
Businessess business = businessVM.CreateBusinessObject()
db.Businesses.AddObject(business);
db.SaveChanges();
return RedirectToAction("Index");
}
2.Directly take form collection as input in your action method in the controller rather than the model/viewmodel and then parse it and create appropriate object.
Upvotes: 1
Reputation: 21365
As an advice, it should be better that you do not try to reuse a single Action
(even when the DRY principle looks appealing)
Even when you could find a way to do it, in the future this would be hard to maintain.
What you are trying to do is:
Treat a Business Hotel, as a Business Restaurant, and any of those as a Business Airport. Do you see what's wrong? a Hotel should have its own Business rules, the same for Airport and Restaurants
If you in the future try to add some specific logic for each one of them, your action method would increase in complexity (BTW the action methods should only call the model to keep them clean).
This is described better in the blue book (DDD)
So my advice is do not reuse ever this kind of logic (Domain logic), I personally try to reuse the infrastructure logic only
Upvotes: 4