c# - ado.net 中的复杂模型绑定
问题描述
我正在从数据库中获取一个表。该表正在使用其他表的连接。我正在努力将它与我的模型绑定。将数据插入两个表都可以正常工作。
我正在从数据库中获取值,但不知道如何将地址转换为列表。
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; }
}
这是我dbcontext
使用 ado.net的课程
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;
}
我从数据库中获取所有值,但我需要将多个地址绑定到地址列表。
解决方案
你可以参考我的解决方案。希望对你有所帮助,新年快乐,我的朋友 :))
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()
});
}
在视图中,您可以像这样显示 cityid:
foreach(var item in peopleslist)
{
var lstCityId = String.Join(",", item.cityid).ToString();
}
推荐阅读
- google-apps-script - for循环不返回数据
- jquery - 模态在控制器中获取正确的路径但未显示
- r - 从存储在列表中的数据帧中绘制多个图
- swift - 从 Firebase 数据库 Swift 中检索嵌套数据
- python - 如何编辑嵌入消息 - discord.py
- ios - 长宽比不隐藏的iOS Swift UIImageView
- jsf - 在 iOS 上卸载页面时在 Omnifaces @ViewScoped bean 上调用 @PreDestroy
- node.js - 使用nodejs时elasticsearch中的文本相似性
- spring-boot - Kustomize configMapGenerator
- mongodb - $addFields MongoDb 中的 $match