简体   繁体   English

一次从多个表获取数据

[英]Get data from multiple tables at once

I used ADO.NET Entity Database Model (auto-generated) for my angularJS application using database model shown below: 我使用如下所示的数据库模型为我的angularJS应用程序使用了ADO.NET实体数据库模型(自动生成):

数据库模型

Currently I am using this code to get all data from Contact table: 目前,我正在使用此代码从Contact表获取所有数据:

ContactsEntities db = new ContactsEntities();

public JsonResult GetAll()
            {
                return Json(db.Contacts.ToList(), JsonRequestBehavior.AllowGet);
            }

What I want to achieve is to get all data from database. 我要实现的是从数据库中获取所有数据。 Is there way to get all data in single "query" or do I need to call 有没有办法在单个“查询”中获取所有数据,还是我需要致电

return Json(db.{MODEL NAME}.ToList(), JsonRequestBehavior.AllowGet);

for each model(table) to get data? 为每个模型(表)获取数据? Is there better solution to get all data from database or do I need to call each model separately? 是否有更好的解决方案从数据库中获取所有数据,还是需要分别调用每个模型?

You should try something like this: 您应该尝试这样的事情:

        var data = (from c in db.Contacts
                    from e in db.Emails.Where(x => x.id == c.id_email).DefaultIfEmpty()
                    from p in db.Phones.Where(x => x.id == c.id_phone).DefaultIfEmpty()
                    from t in db.Tags.Where(x => x.id == c.id_tag).DefaultIfEmpty()
                    select new
                    {
                        id = c.id,
                        phone = p.number,
                        email = e.email1,
                        tag = t.tag1,
                        firstname = c.firstname,
                        lastname = c.lastname,
                        address = c.address,
                        city = c.city,
                        bookmarked = c.bookmarked,
                        notes = c.notes
                    }).ToList();
        return Json(data, JsonRequestBehavior.AllowGet);

Or if you want to prepare yourself for the future, when you add multiple properties to the Contact/Email/... classes and don't want to change your code: 或者,如果您想为将来做准备,请在向Contact / Email / ...类添加多个属性并且不想更改代码时:

        var data = (from c in db.Contacts
                    from e in db.Emails.Where(x => x.id == c.id_email).DefaultIfEmpty()
                    from p in db.Phones.Where(x => x.id == c.id_phone).DefaultIfEmpty()
                    from t in db.Tags.Where(x => x.id == c.id_tag).DefaultIfEmpty()
                    select new
                    {
                        Contact = c,
                        Email = e,
                        Phone = p,
                        Tag = t
                    }).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM