1

私は MVC3 を初めて使用します (これが、MVC3 に関する本を購入した理由であり、この質問が今ある理由です!)。

MVC3 でショッピング カートを作成する簡単な例に従っています。この本は、依存性注入に Ninject を使用することを提唱していますが、これも私は初めてです。1 つのモデル (この場合は Product) で十分に単純に見えますが、これを基に 2 番目のモデルを追加して、Product モデルが表示されている同じビューにこれを表示するのに苦労しています。ビュー モデルを使用してみましたが、見つかったすべての例で複数のクラスが 1 つのモデルにラップされており、これをコードに実装する方法がよくわかりません。

クラス:

public class Product
{
    public int ProductId {get;set;}
    public string Name {get;set;}
}

アブストラクト リポジトリ:

public interface IProductRepository
{
    IQueryable<Product> Products {get;}
}

モデルをデータベースに関連付けるクラス:

public class EFDbContext : DbContext
{
    public DbSet<Product> Products {get;set;}
}

抽象インターフェースを実装する製品リポジトリ:

public class EFProductRepository : IProductRepository
{
    private EFDbContext context = new EFDbContext();

    public IQueryable<Product> Products
    {
        get {return context.Products;}
    }
}

Ninject は、ControllerFactory クラスで IProductRepository を EFProductRepository にバインドします。

コントローラ:

public class ProductController : Controller
{
    private IProductRepository repository;

    public ProductController(IProductRepository productRepository)
    {
        repository = productRepository;
    }

    public ViewResult List()
    {
        return View(repository.Products);
    }
}

私の問題は、repository.Products を強く型付けされたビューに渡すことです。別のエンティティを渡す必要がある場合、これは非常に実現可能です。どうすればこれを達成できますか???

4

2 に答える 2

2

次のようなViewModelを作成できます。

public class YourViewModel
{
    public List<Product> Products { get; set; }
    public List<OtherEntity> OtherEntities { get; set; }
}

次に、リクエストやビジネスロジックを満たすために必要なすべてのメソッドを含むサービスでリポジトリをラップできます。

public class YourService
{
    private IProductRepository repository;

    public List<Product> GetAllProducts( )
    {
        return this.repository.Products.ToList( );
    }

    public List<OtherEntity> GetAllOtherEntites( )
    {
        return this.repository.OtherEntites.ToList( );
    }
}

最後に、コントローラーでViewModelを適切に入力します

public class ProductController : Controller
{
    private YourControllerService service = new YourControllerService( );
    // you can make also an IService interface like you did with
    // the repository

    public ProductController(YourControllerService yourService)
    {
        service = yourService;
    }

    public ViewResult List()
    {
         var viewModel = new YourViewModel( );
         viewModel.Products = service.GetAllProducts( );
         viewModel.OtherEntities = service.GetAllOtherEntities( );

        return View( viewModel );
    }
}

これで、ViewModelに複数のエンティティがあります。

于 2012-08-12T11:27:30.620 に答える