0

我正在扩展(不确定此处是否正确)在 Linq to SQL 数据库模型中生成的部分 Cart 类。

业务逻辑是每个客户只能有一个购物车。如果客户没有购物车,则应该创建它;如果客户有购物车,则应退回。

这就是我正在做的事情:

public partial class Cart
{
    //the rest of the Cart class is in the .dbml file created by L2S
    public Cart(int userId)
    {
        Cart c = GetCurrentCart(userId);
        this.CartId = c.CartId ;
        this.UserId = c.UserId;
    }

    public Cart GetCurrentCart(int userId)
    {
        Cart currentCart = new Cart();

        // if cart exists - get it from DB
        //if not - create it, save in DB, and get if right out
        //all of this is done with Linq to SQL

        return currentCart;
    }
}

从构造函数调用方法似乎并不正确。我是否以正确的方式执行业务逻辑?

4

2 回答 2

8

我会质疑为什么“购物车”类如此聪明。在领域驱动设计术语中,听起来用户“拥有”购物车。那么为什么不这样:

var user = // Load a user
var cart = user.Cart;

在这种情况下,您的 Cart getter 可以延迟加载/初始化购物车。

于 2009-03-12T05:04:34.650 回答
5

我同意 Paul Stovell 的观点,听起来用户应该拥有购物车。但无论如何,当你的构造函数被调用时,你已经有了一个新的 Cart 实例。C# 不允许您更改构造函数返回的引用,因此与其使用构造函数的 Cart 类的客户端,不如调用静态工厂方法(我没有使用 Linq to SQL 的经验,因此这可能行不通直接地)。

您的 GetCurrentCart 方法几乎是这样的;您只需将其标记为静态即可。此外,您应该让 Cart 构造函数只负责创建一个新的 Cart 并将其设为私有,以便客户端被迫使用 GetCurrentCart。一个实现可能看起来像这样:

public partial class Cart
{
        // Make a new cart
        private Cart(int userId, int cartId)
        {
            this.CartId = userId;
            this.UserId = cartId;
        }

        private static Dictionary<int, Cart> CurrentCarts = new Dictionary<int, Cart>();

        public static Cart GetCurrentCart(int userId)
        {
            // TODO: Use a proper caching mechanism that will at least
            //       remove old carts from the dictionary.
            Cart cart;
            if (CurrentCarts.TryGetValue(userId, out cart))
            {
                return cart;
            }

            cart = /* try get cart from DB */;
            if (cart == null)
            {
                // Make a new cart
                cart = new Cart(userId, GenerateCartId());
            }

            CurrentCarts[userId] = cart;

            return cart;
        }
}
于 2009-03-12T05:23:50.313 回答