访问业务对象?

时间:2013-03-29 19:09:43

标签: c#-4.0 lambda asp.net-4.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?

2 个答案:

答案 0 :(得分:1)

您无法在对象初始值设定项中设置类似的嵌套属性。

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

Category = {
    CategoryId = ...
}

答案 1 :(得分: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()
          }

      };
相关问题