【问题标题】:MVC3 correct usage of modelMVC3 正确使用模型
【发布时间】:2011-10-29 08:31:28
【问题描述】:

在查看模型的 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 示例,很多逻辑都在控制器或另一层中,例如数据访问。这样做有什么好处?

谢谢

【问题讨论】:

    标签: asp.net-mvc-3 model


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-09
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多