2014-06-23 93 views
0

我在SQL查詢中遇到了模型邏輯問題。 這是我爲這個項目創建的表格。從m:n關係獲取模型

起初,我的產品表

public partial class Products 
{ 
    public Products() 
    { 
     this.Orders_Products = new HashSet<Orders_Products>(); 
     this.ShoppingCarts_Products = new HashSet<ShoppingCarts_Products>(); 
    } 

    public int ProductId { get; set; } 
    public string Name { get; set; } 
    public double Price { get; set; } 
    public int PPB { get; set; } 
    public int CategoryId { get; set; } 

    public virtual Categories Categories { get; set; } 
    public virtual ICollection<Orders_Products> Orders_Products { get; set; } 
    public virtual ICollection<ShoppingCarts_Products> ShoppingCarts_Products { get; set; } 
} 

然後我的購物表

public partial class ShoppingCarts 
{ 
    public ShoppingCarts() 
    { 
     this.ShoppingCarts_Products = new HashSet<ShoppingCarts_Products>(); 
    } 

    public int ShoppingCartId { get; set; } 
    public string UserId { get; set; } 
    public System.DateTime CreationDate { get; set; } 

    public virtual AspNetUsers AspNetUsers { get; set; } 
    public virtual ICollection<ShoppingCarts_Products> ShoppingCarts_Products { get; set; } 
} 

而且至少連接表之間

public partial class ShoppingCarts_Products 
{ 
    public int ShoppingCartId { get; set; } 
    public int ProductId { get; set; } 
    public int Count { get; set; } 

    public virtual Products Products { get; set; } 
    public virtual ShoppingCarts ShoppingCarts { get; set; } 
} 

現在我需要把所有的列表產品在我自己的ShoppingCart中。 我應該創建什麼樣的模型?

我瘦k我需要寫一個sql語句,其中包括兩個維護者,並將它們與連接表合併。 但我不能在互聯網上找到任何一個人。 有誰知道樣品或可以給我一個提示,如何解決這個問題?

經過這一步後,我需要在佈局網站上顯示該視圖。

好的,我會嘗試使用LINQ to SQL格式編寫查詢。現在,我嘗試將此視圖作爲部分視圖顯示在我的佈局面上。

@Html.Partial("_ShoppingCartPartial", Html.Action("MyShoppingCart","ShoppingCarts")) 

// GET: MyShoppingCart 
    public List<ShoppingCarts_Products> MyShoppingCart() 
    { 

     List<ShoppingCarts_Products> myproducts = db.ShoppingCarts_Products.Where(i => i.ShoppingCartId == 1).ToList();    

     return myproducts; 
    } 

感謝

回答

0

你可以嘗試:

select * from ShoppingCarts_Products 
where ShoppingCarts_Products.ShoppingCartId = <variable> 
left join ShoppingCarts on ShoppingCarts.ShoppingCartId = ShoppingCarts_Products.ShoppingCartId 
left join Products on ShoppingCarts.ProductId = Products.ProductId 

此外,擴大領域選擇標準只選擇你需要的字段。