我使用ADO.NET实体数据库模型(自动生成)为我的angularJS应用程序使用如下所示的数据库模型:
目前我正在使用此代码从Contact表中获取所有数据:
ContactsEntities db = new ContactsEntities();
public JsonResult GetAll()
{
return Json(db.Contacts.ToList(), JsonRequestBehavior.AllowGet);
}
我想要实现的是从数据库中获取所有数据。有没有办法在单个“查询”中获取所有数据,或者我是否需要调用
return Json(db.{MODEL NAME}.ToList(), JsonRequestBehavior.AllowGet);
为每个模型(表)获取数据?是否有更好的解决方案从数据库获取所有数据或我是否需要单独调用每个模型?
答案 0 :(得分:1)
你应该尝试这样的事情:
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);
或者,如果您想为将来做好准备,当您向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();