簡體   English   中英

linq如何獲得按產品分類的顏色?

[英]How can i get the colors by product with linq?

我的色彩課是

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

        public int ColorID { get; set; }
        public string Hex { get; set; }
        public string ColorName { get; set; }
        public int ProductCount { get; set; }

        public virtual ICollection<Products> Products { get; set; }
    }

我的產品類別是

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

    public int ProductID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Colors> Colors { get; set; }
}

如何使用linq按產品獲取顏色並將其設置在ProductCount屬性中?

您已經注意到該類是自動生成的。 可能您不想更改其實現,則可以為Colors類實例添加擴展方法並刪除ProductCount屬性:

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

        public int ColorID { get; set; }
        public string Hex { get; set; }
        public string ColorName { get; set; }

        public virtual ICollection<Products> Products { get; set; }
    }

public static class EntityExtensions
{
    public static int GetProductCount(this Colors colors)
    {
        return colors.Products.Count();
    }
}

然后將其用作:

var productCOunt = colors.GetProductCount();

PS:我建議將Colors實體名稱更改為Color 創建實體時,可以在VS中選擇此選項。

您應該使Products非虛擬Products ,對ProductCount計算,或者完全放棄ProductCount 換句話說, Products是虛擬的時, ProductCount不應保留為手動可設置的屬性。

我選擇刪除ProductCount ,因為您庫的用戶始終可以

myColor.Products.Count

代替

myColor.ProductCount

如果不希望這樣做,請在不使用setter的情況下進行計算所得的屬性:

public int ProductCount => Products.Count; // C# 6

或者如果您使用的是舊語法

public int ProductCount { get { return Products.Count; } }

注意: Color引用所有具有該顏色的產品是很奇怪的,因為要建模的關系是相反的方式(即“一種產品具有顏色”,而不是相反)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM