2013-03-29 48 views
0

我試圖實現類似於'四人幫'設計模式的結構。但我堅持不懈。以下是問題。訪問業務對象?

public class Product 
{ 
    public Product() 
    { 
     Category=new Category(); 
    } 

    public Product(int productId, string productName, string weight, double unitPrice, int unitsInStock) 
     : this() 
    { 
     ProductId = productId; 
     ProductName = productName; 
     Weight = weight; 
     UnitPrice = unitPrice; 
     UnitsInStock = unitsInStock; 
    } 

    public int ProductId { get; set; } 

    public string ProductName { get; set; } 

    public string Weight { get; set; } 

    public double UnitPrice { get; set; } 

    public int UnitsInStock { get; set; } 

    public Category Category { get; set; } 


} 

public class Category : 
{ 

    public Category() 
    { 

    } 
    public Category(int categoryId, string name, string description) 
     : this() 
    { 
     CategoryId = categoryId; 
     Name = name; 
     Description = description; 
    } 

    public int CategoryId { get; set; } 

    public string Name { get; set; } 

    public string Description { get; set; } 

要通過下面的產品清單。

public List<Product> GetProduct() 
    { 
     string sql = 
     @"SELECT ProductId, ProductName, Weight, UnitPrice, UnitsInStock,CategoryId, 
      FROM [Product] 

     return Db.ReadList(sql, Make); 
    } 

private static Func<IDataReader, Product> Make = reader => 
     new Product 
     { 
      ProductId = reader["ProductId"].AsId(), 
      ProductName = reader["ProductName"].AsString(), 
      Weight = reader["Weight"].AsString(), 
      UnitPrice = reader["UnitPrice"].AsDouble(), 
      UnitsInStock = reader["UnitsInStock"].AsInt(), 
      Category.CategoryId=reader["CategoryId].AsInt() 
     }; 

但是,當我寫下面我得到錯誤。

Category.CategoryId=reader["CategoryId].AsInt() 

如何獲取列表中產品的CategoryId?

+0

**錯誤說**是什麼? – SLaks

+0

它顯示錯誤爲'無效的初始化成員聲明'。 –

回答

1

您不能在對象初始值設定項中設置像這樣的嵌套屬性。

相反,你需要設置的子對象的屬性:

Category = { 
    CategoryId = ... 
} 
+0

你可以用上面的例子來指導我的代碼嗎? –

+0

@AbhishekRanjan:你不明白? – SLaks

+0

OK花了幾分鐘才明白你寫的時候的意思。將嘗試並回來。 –

0

的代碼看起來像下面(如果別人需要幫助)。

private static Func<IDataReader, Product> Make = reader => 
     new Product 
     { 
      ProductId = reader["ProductId"].AsId(), 
      ProductName = reader["ProductName"].AsString(), 
      Weight = reader["Weight"].AsString(), 
      UnitPrice = reader["UnitPrice"].AsDouble(), 
      UnitsInStock = reader["UnitsInStock"].AsInt(), 
      Version = reader["Version"].AsBase64String(), 
      Category = 
      { 
       CategoryId = reader["CategoryId"].AsId(), 
       Name = reader["Name"].AsString() 
      } 

     };