我试图通过数据合同发送从数据库中获取的值。因为它的列表iv定义了数据合同中的列表。但我得到了提到的错误。数据合同如下:
[DataContract]
public class a
{
[DataMember]
public string SessionId { get; set; }
[DataMember]
public string StartDate { get; set; }
[DataMember]
public string EndDate { get; set; }
[DataMember]
public string p1 { get; set; }
[DataMember]
public string p2 { get; set; }
[DataMember]
public string p3 { get; set; }
[DataMember]
public string p4 { get; set; }
[DataMember]
public string p5 { get; set; }
[DataMember]
public string p6 { get; set; }
}
[DataContract]
public class b : ReturnValuesBase
{
[DataMember]
public List<a> abc;
}
在我的数据层中,该函数定义如下:
public b Search(string SessionId, string StartDate, string EndDate, string a, string b)
{
b abc = new b();
try
{
SqlConnection CnStr = new SqlConnection();
CnStr = new SqlConnection(ConnString);
CnStr.Open();
SqlCommand cmd = new SqlCommand("[dbo].[abc]", CnStr);
SqlParameter prmSQL = new SqlParameter();
cmd.CommandType = CommandType.StoredProcedure;
DateTime SDate = Convert.ToDateTime(StartDate);
DateTime EDate = Convert.ToDateTime(EndDate);
prmSQL = cmd.Parameters.Add(new SqlParameter("@a", SqlDbType.VarChar, 50));
if (CriticalOptions == "")
{
prmSQL.Value = DBNull.Value;
}
else
{
prmSQL.Value = a;
}
prmSQL = cmd.Parameters.Add(new SqlParameter("@StartDate", SqlDbType.DateTime));
prmSQL.Value = SDate;
prmSQL = cmd.Parameters.Add(new SqlParameter("@EndDate", SqlDbType.DateTime));
prmSQL.Value = EDate;
prmSQL = cmd.Parameters.Add(new SqlParameter("@Ma", SqlDbType.VarChar,50));
prmSQL.Value = a;
SqlDataReader DataReader = cmd.ExecuteReader();
DataSet DS = new DataSet();
SqlDataAdapter DataAdapter = new SqlDataAdapter();
DataAdapter.SelectCommand = cmd;
CnStr.Close();
DataAdapter.Fill(DS);
for (int i = 0; i < DS.Tables[1].Rows.Count; i++)
{
DemoSearchList Demo_List = new DemoSearchList();
Demo_List.a=(Convert.ToString(DS.Tables[1].Rows[i]["a"]));
Demo_List.b=(Convert.ToString(DS.Tables[1].Rows[i]["b"]));
Demo_List.c=(Convert.ToString(DS.Tables[1].Rows[i]["c"]));
Demo_List.d=(Convert.ToString(DS.Tables[1].Rows[i]["d"]));
Demo_List.e=(Convert.ToString(DS.Tables[1].Rows[i]["e"]));
Demo_List.f = SessionId;
Demo_List.g = StartDate;
Demo_List.h = EndDate;
a.abc.Add(Demo_List);
}
}
catch (Exception ex)
{
throw ex;
}
return DemoSearchList;
}
我在这一行得到错误:
DemoSearchList.DemoSearchLists.Add(Demo_List);
任何人都可以帮我解决这个问题
答案 0 :(得分:1)
DemoSearchList.DemoSearchLists为null。在使用之前,您需要为其致电new
:
DemoSearchList.DemoSearchLists = new List<DemoSearchList>();
答案 1 :(得分:1)
您需要添加此行
if(DemoSearchList.DemoSearchLists == null)
DemoSearchList.DemoSearchLists = new List<DemoSearchList>();
之前
DemoSearchList.DemoSearchLists.Add(Demo_List);
答案 2 :(得分:0)
这还不够:
DemoList DemoSearchList = new DemoList();
您还需要初始化其成员DemoSearchLists
,然后才能使用它。
DemoSearchLists.DemoSearchLists = new List<DemoSearchList>();
答案 3 :(得分:0)
DemoSearchList.DemoSearchLists = null。在使用之前,您需要调用new:
DemoList DemoSearchList = new DemoList();
DemoSearchList.DemoSearchLists = new List<DemoSearchList>();