0

Linq to SQL データベース モデルで生成された部分的な Cart クラスを拡張しています (ここで正しい言葉かどうかはわかりません)。

ビジネス ロジックは、顧客ごとに 1 つのカートしか存在できないということです。顧客がカートを持っていない場合は、カートを作成する必要があります。顧客がカートを持っている場合は、カートを返却する必要があります。

これが私がやっていることです:

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

5

Paul Stovell に同意します。ユーザーがカートを所有する必要があるようです。しかし、いずれにしても、コンストラクターが呼び出されるまでには、既に Cart の新しいインスタンスが作成されています。C# では、コンストラクターによって返される参照を変更できないため、コンストラクターを使用する Cart クラスのクライアントではなく、静的ファクトリ メソッドを呼び出す必要があります (Linq to SQL の経験がないため、これは機能しない可能性があります)。直接)。

GetCurrentCart メソッドはほぼこれです。静的とマークするだけです。さらに、カート コンストラクターが新しいカートの作成のみを担当するようにし、それをプライベートにして、クライアントが 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 に答える