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?

4

2 回答 2

1

您不能在对象初始值设定项中设置这样的嵌套属性。

相反,您需要在子对象上设置属性:

Category = {
    CategoryId = ...
}
于 2013-03-29T19:16:21.497 回答
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()
          }

      };
于 2013-03-29T20:08:41.227 回答