遍历多个模型中的记录

时间:2019-11-06 09:41:09

标签: sql-server asp.net-mvc razor-pages

我一直试图显示四个表中的数据。我已经看到<script> function traverse(target, callback){ if(target.nodeType === 1){ callback(target); var c = target.childNodes; for(var i=0; i<c.length; i++){ /* recursive function here */ traverse(c[i], callback); } } } traverse(document.querySelector('body'), function(elem){ console.log(elem); }); </script> ,并且还创建了一个类IEnumerable<>,该类将所有三个类放在一起。其目的是按照SingleModel的显示记录参数。但是我总是出错

  

对象引用未设置为对象的实例”

在此行代码上

Telephone

在控制器上

控制器:

join ct in x3 on st.ID equals ct.ID into table2

模型:

    public ActionResult Details(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
        }

        List<SingleView> x1 = db.SingleViews.Where(a => a.Telephone == id).ToList();
        List<SingleViewM> x2 = db.SingleViewMs.Where(a => a.Telephone == id).ToList();
        List<SingleViewWst> x3 = db.SingleViewWsts.Where(a => a.Telephone == id).ToList();
        List<PensionsView> x4 = db.PensionsViews.Where(a => a.Telephone == id).ToList();

        var multipletables = from c in x1
                             join st in x2 on c.ID equals st.ID into table1
                             from st in table1.DefaultIfEmpty()
                             join ct in x3 on st.ID equals ct.ID into table2
                             from ct in table2.DefaultIfEmpty()
                             select new SingleModel { USSD = c, Mombasa = st, Western = ct };

        return View(multipletables);
    }

视图:

public class SingleModel
{
    public SingleView USSD { get; set; }
    public SingleViewM Mombasa { get; set; }
    public SingleViewWst Western { get; set; }
    public PensionsView PensionsViews{ get; set; }
}

1 个答案:

答案 0 :(得分:0)

具有left join意味着如果第二个表中没有匹配的记录,则所有这些值均为null(与常规join不同,它将不会从左表)。该记录的st等于null,因此您必须对其进行检查

尝试一下:

   public ActionResult Details(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
        }

        List<SingleView> x1 = db.SingleViews.Where(a => a.Telephone == id).ToList();
        List<SingleViewM> x2 = db.SingleViewMs.Where(a => a.Telephone == id).ToList();
        List<SingleViewWst> x3 = db.SingleViewWsts.Where(a => a.Telephone == id).ToList();
        List<PensionsView> x4 = db.PensionsViews.Where(a => a.Telephone == id).ToList();

        var multipletables = from c in x1
                             join st in x2 on c.ID equals st.ID into table1
                             from st in table1.DefaultIfEmpty()
                             join ct in x3 on st?.ID equals ct?.ID into table2
                             from ct in table2.DefaultIfEmpty()
                             select new SingleModel { USSD = c, Mombasa = st, Western = ct };

        return View(multipletables);
    }

还可以在您的?.中使用select new