はどうやらProductSuppliersTableからごSupplierTableとProductSupplier項目からサプライヤー項目間の1対多の関係があります:
すべてのサプライヤーがゼロ以上ProductSuppliersを持ち、すべてのProductSupplierは正確に一つのサプライヤーに属します。
あなたのone-to-many relationship according to the default entity framework conventions次のようなクラスがあります設定した場合:
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;}
...
}
をそれはいくつかの識別子名が異なることかもしれないが、アイデアが明確である:あなたのサプライヤーは、仮想ICollectionをする必要がProductSuppliers、およびProductSupplierには、サプライヤおよび仮想サプライヤに対する外部キーが必要です。
これを正しく実行すると、エンティティフレームワークはプライマリキーと外部キーを認識し、正しいテーブルを作成します。
あなたのDbContextとあなたのDbSetsがこの1対多の関係について知っていることは素晴らしいことです。 ProductSuppliersを持つサプライヤが必要なときはいつでも、外部キーのジョインを実行する必要はありません。代わりにICollectionを使用できます。
あなたが望むものを自分の言い回しにします。
私はサプライヤーの名前を持っていると私は一緒にサプライヤーの ProductSuppliersからすべてSupplierRefsと、この 名に等しいトリム小文字の名前を持つ 私SupplierTableから最初のサプライヤーのアイテムが欲しいです。
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();
}
}
エンティティフレームワークは、あなたの1対多の知っている、とその外部キーは、このために使用されます。 Entity Frameworkは適切な結合を行い、あなたのために選択します。
これらの2つのテーブルを結合します。 –
最初のクエリを取得して、「supplierID」を持つ2番目のクエリに入れます – CodingYoshi