我正在从数据库中获取表。该表正在使用其他表的联接。我正在努力将其与我的模型绑定。将数据插入到两个表中都有效。
我正在从数据库中获取值,但不知道如何将地址转换为列表。
public class address
{
public int id { get; set; }
public string peopleaddress { get; set; }
}
public class People
{
public int id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string address { get; set; }
public List<string> cityid { get; set; } // is equal to people address
public string shortimagepath { get; set; }
public string fullimagepath { get; set; }
}
这是我使用ado.net的dbcontext
类
public List<People> selectallpeople()
{
List<People> peopleslist = new List<People>();
List<address> addresses = new List<address>();
using (SqlConnection sqlConnection=new SqlConnection(dbconnect))
{
SqlCommand sqlCommand = new SqlCommand("selectallpeople", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
DataTable datatable = new DataTable();
sqlDataAdapter.Fill(datatable);
foreach (DataRow item in datatable.Rows)
{
addresses.Add(new address
{
peopleaddress = item["address"].ToString(),
});
peopleslist.Add(new People
{
id = (int)item["id"],
Name = item["name"].ToString(),
LastName = item["lastname"].ToString(),
shortimagepath = item["imageshortpath"].ToString(),
// I am struggling here to bind address column to list of address
});
}
return peopleslist;
}
我从数据库中获取所有值,但是我需要将多个地址绑定到地址列表。
答案 0 :(得分:0)
您可以参考我的解决方案。希望对大家有帮助,新年快乐,我的朋友:))
foreach (DataRow item in datatable.Rows)
{
int idObj = (int)item["id"] //This Id for both, right?
addresses.Add(new address
{
id = idObj,
peopleaddress = item["address"].ToString(),
});
peopleslist.Add(new People
{
id = (int)item["id"],
Name = item["name"].ToString(),
LastName = item["lastname"].ToString(),
shortimagepath = item["imageshortpath"].ToString(),
// I am struggling here to bind address column to list of address
cityid = addresses.Where(t => t.id == idObj)
.Select(t=>t.peopleaddress.ToString()).ToList()
});
}
在视图中,您可以这样显示城市ID:
foreach(var item in peopleslist)
{
var lstCityId = String.Join(",", item.cityid).ToString();
}