LINQ:有没有办法将这些查询合并为一个?

use*_*144 7 c# linq sql-server asp.net asp.net-mvc

我有一个包含3个表的数据库:

  • 手机
  • PhoneListings
  • PhoneConditions

PhoneListings具有来自电话表(PhoneID)的FK,以及来自电话条件表(conditionID)的FK

我正在开发一个功能,将电话列表添加到用户的购物车,并返回用户的所有必要信息.电话品牌和型号包含在PHONES表中,有关条件的详细信息包含在PhoneConditions表中.

目前我使用3个查询来获取所有必要的信息.有没有办法将所有这些组合成一个查询?

public ActionResult phoneAdd(int listingID, int qty)
{

    ShoppingBasket myBasket = new ShoppingBasket();
    string BasketID = myBasket.GetBasketID(this.HttpContext);



     var PhoneListingQuery = (from x in myDB.phoneListings
                             where x.phonelistingID == listingID
                             select x).Single();

     var PhoneCondition = myDB.phoneConditions
                          .Where(x => x.conditionID == PhoneListingQuery.phonelistingID).Single();

    var PhoneDataQuery = (from ph in myDB.Phones
                          where ph.PhoneID == PhoneListingQuery.phonePageID
                          select ph).SingleOrDefault();

}
Run Code Online (Sandbox Code Playgroud)

Stu*_*tLC 5

您可以将结果投影到匿名类或元组,甚至是单行中的自定义形状实体,但整体数据库性能可能不会更好:

var phoneObjects = myDB.phoneListings
       .Where(pl => pl.phonelistingID == listingID)
       .Select(pl => new 
       {
          PhoneListingQuery = pl,
          PhoneCondition = myDB.phoneConditions
             .Single(pc => pc.conditionID == pl.phonelistingID),
          PhoneDataQuery = myDB.Phones
             .SingleOrDefault(ph => ph.PhoneID == pl.phonePageID)
       })
       .Single();

  // Access phoneObjects.PhoneListingQuery / PhoneCondition / PhoneDataQuery as needed
Run Code Online (Sandbox Code Playgroud)

LINQ SingleSingleOrDefault扩展的重载也稍微紧凑,它将谓词作为参数,这将有助于略微减少代码.

编辑

作为从ORM进行多次检索DbContext或执行显式手动Join的替代方法,如果通过可导航连接键(通常是基础表中的外键)在模型中的实体之间设置导航关系,则可以指定获取的深度使用Include:急切加载

var phoneListingWithAssociations = myDB.phoneListings
       .Include(pl => pl.PhoneConditions)
       .Include(pl => pl.Phones)
       .Single(pl => pl.phonelistingID == listingID);
Run Code Online (Sandbox Code Playgroud)

这将返回phoneListingWithAssociations中的实体图

(假设外键PhoneListing.phonePageID => Phones.phoneIdPhoneCondition.conditionID => PhoneListing.phonelistingID)