While looking at MVC3 examples of models. Most people tend to use model classes to create class definitions for business objects to hold data with very little or no logic. The sole purpose of model then is to be passed around. For example:
namespace MvcMusicStore.Models
{
public class Cart
{
[Key]
public int RecordId { get; set; }
public string CartId { get; set; }
public int AlbumId { get; set; }
public int Count { get; set; }
public System.DateTime DateCreated { get; set; }
public virtual Album Album { get; set; }
}
}
Is this how models classes should typically be used in MVC? Sometimes I see logic but are very specific to manipulating data. For exmaple:
public partial class ShoppingCart
{
MusicStoreEntities storeDB = new MusicStoreEntities();
string ShoppingCartId { get; set; }
public const string CartSessionKey = "CartId";
public static ShoppingCart GetCart(HttpContextBase context)
{
var cart = new ShoppingCart();
cart.ShoppingCartId = cart.GetCartId(context);
return cart;
}
// Helper method to simplify shopping cart calls
public static ShoppingCart GetCart(Controller controller)
{
return GetCart(controller.HttpContext);
}
public void AddToCart(Album album)
{
// Get the matching cart and album instances
var cartItem = storeDB.Carts.SingleOrDefault(
c => c.CartId == ShoppingCartId
&& c.AlbumId == album.AlbumId);
if (cartItem == null)
{
// Create a new cart item if no cart item exists
cartItem = new Cart
{
AlbumId = album.AlbumId,
CartId = ShoppingCartId,
Count = 1,
DateCreated = DateTime.Now
};
storeDB.Carts.Add(cartItem);
}
else
{
// If the item does exist in the cart, then add one to the quantity
cartItem.Count++;
}
// Save changes
storeDB.SaveChanges();
}
}
What is the correct way of using the Model? In classic MVC definition, model is where the intelligence of the application should be. However looking at MVC3 samples, a lot of logic is in controller or another layer for say Data Access. What is the advantage of this?
Thanks
The short answer is it provides for separation of model definitions and data access, which are conceptually different. When you separate your Data Access to its own layer (not as part of either controllers or models) you achieve far greater De-coupling.
That said there are a lot of different ways developers are using MVC, and model as data accessors is definitely one of them – the framework even supports models based on entity framework; go straight from the database to a usable model.
There’s always the “fat controller” pattern of course; that is, stick all your handling logic inside the controller. I wouldn’t recommend that because it will very quickly spiral into unmaintainable code.