我的情况是,我希望在我看来有两个模特。我一直在尝试这样做,如下面的控制器,但我不知道如何正确的方式来做到这一点,但我假设它是一个做一个WellViewModel的实例,然后创建并添加到各个列表,WellViewModel包含但我认为我已经糊涂了一点,因为我似乎无法让它工作。任何提示?
这些是我放入ViewModel的模型:
public class WellViewModel
{
public List<WellModel> Wells { get; set; }
public List<AnnotationModel> Annotations { get; set; }
}
这是我从数据库中检索数据的地方:
public ActionResult Well(string slideid)
{
WellViewModel model = new WellViewModel();
string cs = dbPath;
using (SQLiteConnection con = new SQLiteConnection(cs))
{
string stm = "SELECT * FROM Well WHERE SlideId = " + "'" + slideid + "'";
con.Open();
using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
{
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
model.Wells = new List<WellModel>() { new WellModel()} //This is not possible to do
{
SlideId = rdr["SlideId"].ToString(),
Well = int.Parse(rdr["Well"].ToString()),
TimeStamp = rdr["TimeStamp"].ToString()
};
}
rdr.Close();
}
}
con.Close();
}
using (SQLiteConnection con = new SQLiteConnection(cs))
{
string stm = "SELECT * FROM Annotation WHERE SlideId = " + "'" + slideid + "'";
con.Open();
using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
{
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Annotations = new AnnotationModel
{
SlideId = rdr["SlideId"].ToString(),
Well = int.Parse(rdr["Well"].ToString()),
Par = rdr["Par"].ToString(),
Time = rdr["Time"].ToString(),
Val = rdr["Val"].ToString(),
TimeStamp = rdr["TimeStamp"].ToString()
};
}
rdr.Close();
}
}
con.Close();
}
return View(model);
}
答案 0 :(得分:3)
在while
循环中,您创建一个新的List<WellModel>
并添加一个项目。
相反,定义如下:
WellViewModel model = new WellViewModel();
model.Wells = new List<WellModel>();
model.Annotations = new List<AnnotationModel>();
while (rdr.Read())
{
model.Wells.Add(new WellModel { // set values here };
}
对List
的其他Annotations
执行相同操作。
答案 1 :(得分:2)
我看到你的代码唯一的问题是使用不当或读者用数据填充列表。您应该在阅读循环之外初始化一个列表,然后只需向其中添加新项目:
model.Wells = new List<WellModel>();
using (SQLiteConnection con = new SQLiteConnection(cs))
{
....
while (rdr.Read())
{
WellModel well = new WellModel
{
SlideId = rdr["SlideId"].ToString(),
Well = int.Parse(rdr["Well"].ToString()),
TimeStamp = rdr["TimeStamp"].ToString()
};
model.Wells.Add(well);
}
同样适用于其他名单。
答案 2 :(得分:2)
我认为,如果您向Constructor
添加WellViewModel
,那么您可以将WellModel List
设置为AnnotationModel List
。
像这样:
public class WellViewModel
{
public WellViewModel()
{
Wells = new List<WellModel>();
Annotaions = new List<AnnotationModel>();
}
public List<WellModel> Wells { get; set; }
public List<AnnotationModel> Annotations { get; set; }
}
在您的while循环中,您只需添加新的WellModel
/ AnnotationModel
。
while (rdr.Read())
{
model.Wells.Add(new WellModel()
{
// set values here
});
}