[英]How do i combine 2 Linq queries into 1?
参数-(字符串供应商)
var supplierID = db.SupplierTable
.Where(m => m.SupplierName.Trim().ToLower() == Supplier.Trim().ToLower())
.Select(m => m.SupplierID).First();
var supplierREFs = db.ProductSuppliers
.Where(m => m.SupplierID == supplierID)
.Select(m => m.SupplierRef);
可以将以上2个查询合并为1个查询?
当然,您需要一个子查询:
Supplier = Supplier.Trim(); // do this once and not in the query
var supplierREFs = db.ProductSuppliers
.Where(m => db.SupplierTable
.Where(s => m.SupplierID == s.SupplierID)
.Any(s => String.Equals(s.SupplierName.Trim(), Supplier, StringComparison.CurrentCultureIgnoreCase))
)
.Select(m => m.SupplierRef);
该查询采用每个SupplierName
匹配给定Supplier
ProductSupplier
(忽略大小写)。 然后返回它的SupplierRef
。
边注:如果你不存储SupplierNames
与数据库中的前/后间隔应该比不上s.SupplierName.Trim()
但s.SupplierName
。
您可以使其加入两个实体,例如;
Supplier = Supplier.Trim().ToLower();
var supplierREFs = (from st in db.SupplierTable
join sr in supplierREFs on st.SupplierID equals sr.SupplierID
where
st.SupplierName.Trim().ToLower() == Supplier
select sr)
显然,您的SupplierTable中的Supplier项目与ProductSuppliersTable中的ProductSupplier项目之间存在一对多关系:
每个供应商都有零个或多个产品供应商,每个产品供应商恰好属于一个供应商。
如果您已根据默认实体框架约定配置了一对多关系,则将具有类似于以下内容的类:
class Supplier
{
public int Id {get; set;}
// Every Supplier has zero or more ProductSupplierTables:
public virtual ICollection<ProductSuppierTable> ProductSupplierTables {get; set;}
public string SupplierName {get; set;}
...
}
class ProductSupplier
{
public int Id {get; set;}
// every ProductSupplier belongs to exactly one Supplier using foreign key
public virtual Supplier Supplier {get; set;}
public int SupplierId {get; set;}
public string SupplierRef {get; set;}
...
}
可能是某些标识符名称有所不同,但思路很明确:您的供应商需要ProductSuppliers的虚拟ICollection,而您的ProductSupplier需要供应商以及虚拟供应商的外键。
一旦正确完成此操作,实体框架就会知道主键和外键并为您创建正确的表。
令人高兴的是,您的DbContext和DbSet知道这种一对多的关系。 只要您需要供应商及其产品供应商,就不需要对外键执行联接。 您可以改用ICollection。
改写自己想要的内容。
我有一个供应商的名称,我希望我的SupplierTable中的第一个Supplier项具有等于该名称的Trimated LowerCase名称,以及供应商的ProductSuppliers的所有SupplierRef。
using (var dbContext = new MyDbContext())
{
string supplierName = Supplier.Trim().ToLower()
dbContext.Suppliers
.Where(supplier => String.ToLower(supplier.SupplierName) == supplierName)
.Select(supplier => new
{ // to improve performance: select only the properties you'll use
SupplierId = supplier.Id,
...
// select also all the SupplierRefs from its ProductSuppliers:
SupplierRefs = supplier.ProductSupplier
.Select(productSupplier => productSupplier.SupplierRef)
.ToList(),
})
// I only want the First (or default) of these suppliers:
.FirstOrDefault();
}
}
实体框架知道您的一对多关系,并且使用哪个外键。 实体框架将进行适当的联接并为您选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.