jureispro
jureispro

Reputation: 1402

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:

Database model

Currently I am using this code to get all data from Contact table:

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?

Upvotes: 0

Views: 980

Answers (1)

John
John

Reputation: 3702

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:

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

Upvotes: 1

Related Questions