我有一个应用程序,学生可以使用它来选择他们想要加入的大学,在应用程序中,我们目前提供最多选择3所大学的选项,我们说第一首选,第二首选和第三首选,我们有一个存储过程,返回数据和结果集的列如下。
UserId | FirstName | LastName | Email | Mobile | City |
FirstPreferredCollegeId | FirstPreferredCollegeName |
FirstPreferredCollegeGrade | FirstPreferredCollegePincode |
SecondPreferredCollegeId | SecondPreferredCollegeName |
SecondPreferredCollegeGrade | SecondPreferredCollegePincode |
ThirdPreferredCollegeId | ThirdPreferredCollegeName |
ThirdPreferredCollegeGrade | ThirdPreferredCollegePincode |
如果我们看上面的结果集UserId, FirstName, LastName, Email, Mobile, City是唯一的,其中PreferredCollegeId, PreferredCollegeName, PreferredCollegeGrade, PreferredCollegePinCode重复三次。
我的c#模型如下所示:
Public Class User
{
Public int UserId {get;set;}
Public string FirstName {get;set;}
public string LastName {get;set;}
public string Email {get;set;}
public string Mobile {get;set;}
public string City {get;set;}
public List<Choice> Choices {get;set;}
}
public class Choice
{
public string PreferredCollegeId {get;set;}
public string PreferredCollegeName {get;set;}
public string PreferredCollegeGrade {get;set;}
public string PreferredCollegePincode {get;set;}
}
现在ADO。. NET代码如下所示,阅读器为SqlDataReader
对象。
objUser.UserId = (string)reader["UserId"];
objUser.FirstName = (string)reader["FirstName"];
objUser.LastName = (string)reader["LastName"];
objUser.Email = (string)reader["Email"];
objUser.Mobile = (string)reader["Mobile"];
objUser.City = (string)reader["City"];
/* Here I need to loop through reader and get College details
Choice ch = new Choice();
现在我需要通过SqlDataReader
循环并获得PreferredCollegeId, PreferredCollegeName, PreferredCollegeGrade, PreferredCollegePincode并动态创建一个选择类的对象并将这些值绑定到选择对象-我如何实现这一点?
试试这样:
var prefixes = new List<string> {"First", "Second", "Third"};
objUser.Choices = new List<Choice>();
foreach(var prefix in prefixes)
{
objUser.Choices.Add(new Choice {
PreferredCollegeId= (string) reader[prefix + "PreferredCollegeId"],
PreferredCollegeName = (string) reader[prefix + "PreferredCollegeName"],
PreferredCollegeGrade = (string) reader[prefix + "PreferredCollegeGrade"],
PreferredCollegePincode = (string) reader[prefix + "PreferredCollegePincode"]
});
}