在查询中多次使用相关实体

时间:2015-04-26 18:24:22

标签: .net vb.net entity-framework linq-to-entities entity-relationship

我正在尝试将两个表的列表放入一个我制作的泛型类的列表中。

我的问题是如何在不为每个字段调用firstOrDefault的情况下从相关表中获取字段,请参阅示例代码,我需要一个非常长的字段价格和成本,我还有一些要做的事情.. 。

    Dim items As IQueryable(Of ItemMain)


    Return items.Where(Function(i) i.Status > -1).Select(Function(x) New ItemViewBasic() With {.ItemID = x.ItemID,
                                                                      .Name = x.Name,
                                                                      .BarcodeNumber = x.BarcodeNumber,
                                                                      .Price = x.ItemStores.Where(Function(itemStore) itemStore.StoreNo = GlobalValues.StoreID).FirstOrDefault().Price,
                                                                      .Cost = x.ItemStores.Where(Function(itemStore) itemStore.StoreNo = GlobalValues.StoreID).FirstOrDefault().Cost})

2 个答案:

答案 0 :(得分:3)

在关于使用let关键字的评论中从@ Jeroen-Vannevel获得提示后,我想到了如何做到这一点。我在这里发布以供将来参考..

      Return (From i In items Let itemStore = i.ItemStores.Where(Function(its) its.StoreNo = GlobalValues.StoreID And its.Status > -1).FirstOrDefault() Where i.Status > -1
            Select New ItemViewBasic With {.ItemID = i.ItemID,
                                           .Name = i.Name,
                                           .Cost = itemStore.Cost,
                                           .BarcodeNumber = i.BarcodeNumber,
                                           .OnHand = itemStore.OnHand,
                                           .Department = itemStore.DepartmentID,
                                           .Price = itemStore.Price,
                                           .ModalNumber = i.ModalNumber})

答案 1 :(得分:1)

我将使用的方法(在C#中)首先为有问题的商店生成ItemStore记录的查询,例如。

uname -a
Darwin mbarton-lm.local 13.4.0 Darwin Kernel Version 13.4.0: Wed Mar 18 16:20:14 PDT 2015; root:xnu-2422.115.14~1/RELEASE_X86_64 x86_64 i386 MacBookPro9,1 Darwin

ghc -v
Glasgow Haskell Compiler, Version 7.8.4, stage 2 booted by GHC version 7.8.3
Using binary package database: /usr/local/Cellar/ghc/7.8.4/lib/ghc-7.8.4/package.conf.d/package.cache
wired-in package ghc-prim mapped to ghc-prim-0.3.1.0 a24f9c14c632d75b683d0f93283aea37
wired-in package integer-gmp mapped to integer-gmp-0.5.1.0-26579559b3647acf4f01d5edd9491a46
wired-in package base mapped to base-4.7.0.2-99f2b20e2491b27225d4c673401d826f
wired-in package rts mapped to builtin_rts
wired-in package template-haskell mapped to template-haskell-2.9.0.0-c0be869a24cf2c4fa8e8cbf52d0324ff
wired-in package dph-seq not found.
wired-in package dph-par not found.

cabal -V
cabal-install version 1.22.0.0
using version 1.22.0.0 of the Cabal library

然后将其加入您已有的项目:

var itemStores = myDbContext.ItemStores.Where(i => i.StoreNo = GlobalValues.StoreID);