MVC3正确使用模型

时间:2011-10-29 00:20:25

标签: asp.net-mvc-3 model

同时看MVC3的模型示例。大多数人倾向于使用模型类来为业务对象创建类定义,以便用很少或没有逻辑来保存数据。那么模型的唯一目的就是传递。例如:

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; }
    }
}

这是模型类通常应该如何在MVC中使用?有时候我会看到逻辑但是非常特定于操纵数据。例如:

    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();
        }
}

使用该模型的正确方法是什么?在经典的MVC定义中,模型是应用程序的智能所在。无论如何看MVC3样本,很多逻辑都在控制器或另一层用于数据访问。这有什么好处?

由于

1 个答案:

答案 0 :(得分:0)

简短的回答是它提供了模型定义和数据访问的分离,这在概念上是不同的。将数据访问分离到自己的层(而不是控制器或模型的一部分)时,可以实现更大的解耦。

也就是说开发人员使用MVC的方式有很多种,而作为数据访问者的模型肯定是其中之一 - 框架甚至支持基于实体框架的模型;直接从数据库转到可用的模型。

当然,总有“胖控制器”模式;也就是说,将所有处理逻辑都放在控制器中。我不建议这样做,因为它会很快变成不可维护的代码。