从一个db表读取并将其存储在2个对象中

时间:2012-06-19 14:48:57

标签: c# asp.net sql-server visual-studio-2010 web

这两种方法遇到问题

我想返回csVehicle和csDistributor的对象 因为我下面的代码只返回csVehicle

请帮助

public List<csVehicle> get_All_Vehicles()
{            
    var objv = new List<csVehicle>(); 
    IDataReader dr = null;
    var objdal = new csDAL();
    dr = objdal.executespreturndr("sp_Get_All_Distributor");
    while (dr.Read())
    {
        var d = new csDistributor();     // I put this here so that I can use the propDistrbutorId
        var v = new csVehicle();
        populate_Data(dr, d,v);
        objv.Add(v);                    //It only adds object of csVehicles and csDistributor is not added
    }
    return objv;                        // csDistributor is not returned
}

populate_Date方法将数据添加到两个对象csDistributor和csVehicle

private void populate_Data(IDataReader dr, csDistributor d, csVehicle v)
{
    v._vehicleRegNo = dr["VehicleRegNo"].ToString();
    d.propDistrbutorId = Convert.ToInt32(dr["DistrbutorId"]);                      
}

1 个答案:

答案 0 :(得分:0)

这是一个简单的解决方案:

public List<object> get_All_Vehicles()
{            
    var objv = new List<object>(); 
    IDataReader dr = null;
    var objdal = new csDAL();
    dr = objdal.executespreturndr("sp_Get_All_Distributor");
    while (dr.Read())
    {
        var d = new csDistributor();
        var v = new csVehicle();
        populate_Data(dr, d,v);
        objv.Add(v);                
        objv.Add(d);    
    }
    return objv;                        
}

更复杂的解决方案是定义csDistributor和csVehicle继承的父类,然后返回该特定类型的List<>

或者使用ArrayList,它只是一个无类型的对象集合。

编辑:我不得不猜测您的代码在其他地方的使用方式,但请尝试以下方法:

public void get_All_Vehicles(out csVehicle vehicle, out csDistributor distributor)
{            
    vehicle = new List<csVehicle>(); 
    distributor = new List<csDistributor>();
    IDataReader dr = null;
    var objdal = new csDAL();
    dr = objdal.executespreturndr("sp_Get_All_Distributor");
    while (dr.Read())
    {
        var d = new csDistributor();
        var v = new csVehicle();
        populate_Data(dr, d,v);
        vehicle.Add(v);                
        distributor.Add(d);    
    }
}