1

我正在创建一个 Web 应用程序,我有两个类:

public class MOrderMain
{
    public int ID { get; set; }
    public int CompanyID { get; set; }
    public string CompanyName { get; set; }
    public DateTime OrderDate { get; set; }
    public string BillingName { get; set; }
    public string BillingAddress { get; set; }
    public string DeliveryName { get; set; }
    public string DeliveryAddress { get; set; }
}

public class MOrder
{
   public int ID { get; set; }
   public int OrhID { get; set; }
   public int ProID { get; set; }
   public string Name { get; set; }
   public int Quantity { get; set; }
   public double Rate { get; set; }
   public double Amount { get; set; }
   public int DeliveredQty { get; set; }
}

我想从这两个类中检索详细信息。例如,我想 从 classID和class 中获取所有属性。我怎样才能做到这一点?Billing NameMorderMainMOrder

我正在通过数据库获取值。我有查询,但我将如何分配数据以及如何从两者中检索?

var mylist = new List<MOrder>();
_con = _db.GetConnection();
if (_con.State.Equals(ConnectionState.Closed))
{
    _con.Open();
}
_cmd = new SqlCommand("Get_All_Order_Details", _con) 
           { CommandType = CommandType.StoredProcedure };
_dr = _cmd.ExecuteReader();

while (_dr.Read())
{
    mylist.Add(new MOrder
    {
        ID = Convert.ToInt32(_dr["ordID"]),
        OrhID = Convert.ToInt32(_dr["orhID"]),
        ProID = Convert.ToInt32(_dr["proID"]),
        Name = _dr["pName"].ToString(),
        Quantity = Convert.ToInt32(_dr["ordQty"]),
        Rate = Convert.ToDouble(_dr["ordRate"]),
        Amount = Convert.ToDouble(_dr["ordAmount"]),
        DeliveredQty = Convert.ToInt32(_dr["ordQtyDelivered"])
     });
}
return mylist;
4

1 回答 1

0

由于您要从数据库中的两个表中检索数据,但希望将它们组合到应用程序中,因此解决方案是创建一个包含从存储过程返回的数据的单个类:

public class MAllOrderDetails
{
   public int ID { get; set; }
   public string BillingName { get; set; }
   // include the other billing details you want here

   public int OrhID { get; set; }
   public int ProID { get; set; }
   public string Name { get; set; }
   public int Quantity { get; set; }
   public double Rate { get; set; }
   public double Amount { get; set; }
   public int DeliveredQty { get; set; }
}

然后,您的查询更改为填写List<MAllOrderDetails>.

这使您的应用程序只需要处理单个类的集合,所有数据都很好地包含在单个对象中。

var mylist = new List<MAllOrderDetails>();
//...
while (_dr.Read())
{
    mylist.Add(new MAllOrderDetails
    {
        ID = Convert.ToInt32(_dr["ordID"]),
        BillingName = _dr["BillingName"].ToString(),
        // etc.
        OrhID = Convert.ToInt32(_dr["orhID"]),
        ProID = Convert.ToInt32(_dr["proID"]),
        Name = _dr["pName"].ToString(),
        Quantity = Convert.ToInt32(_dr["ordQty"]),
        Rate = Convert.ToDouble(_dr["ordRate"]),
        Amount = Convert.ToDouble(_dr["ordAmount"]),
        DeliveredQty = Convert.ToInt32(_dr["ordQtyDelivered"])
     });
}

更新

作为不创建其他类的最接近的解决方案,您可能会侥幸逃脱:

class MAllOrderDetails
{
    public MOrder Order { get; set; }
    public MOrderMain OrderMain { get; set; }
}

不过,我觉得,从可维护性的角度来看,这会比仅仅创建额外的类更让你头疼。

于 2012-08-29T16:39:48.793 回答