首页 > 解决方案 > 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;
        }

我从数据库中获取所有值,但我需要将多个地址绑定到地址列表。

标签: c#sqlasp.netsql-serverasp.net-mvc

解决方案


你可以参考我的解决方案。希望对你有所帮助,新年快乐,我的朋友 :))

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();    
}

推荐阅读