2016-04-25 19 views
1

In einem Projekt, an dem ich arbeite, habe ich eine Datenbank (die ich nicht ändern kann) mit zwei Tabellen (Item und ItemSupplier). In der Datenbank befindet sich kein Fremdschlüssel. In meinem EF6 Ich habe zwei Objekte erstellt (Datenbank zuerst):Holen Sie sich eine Sammlung basierend auf der Eigenschaft einer anderen Sammlung mit Linq

public class Item { 
    public string ItemCode { get; set;} 
    public string Description { get; set; } 
    public double SalesPrice { get; set; } 
} 

public class ItemSupplier { 
    public string ItemCode { get; set; } 
    public string AccountCode { get; set; } 
} 

Was ich will, ist eine Liste von Item, die zu einem bestimmten Lieferanten gehört. So war meine Idee, zunächst eine Liste von ItemSupplier zu bekommen und dann bekommen die Item Liste mit Any():

public List<Item> GetItemsByAccountCode(string code) 
{ 
    List<Item> itemList = new List<Item>(); 
    using(DbEntities context = new DbEntities()) 
    { 
     // Get the list of items of a specific supplier 
     List<ItemSupplier> itemSupList = context.ItemSupplier.Where(p => 
              p.AccountCode == code).ToList(); 

     // Get al the items based on the itemSupList 
     // Below is not working 
     itemList = context.Item.Where(p => itemSupList.Any(x => x.ItemCode)); 
    } 
} 

Antwort

0

Also meine Idee war, zunächst eine Liste bekommen von ItemSupplier und dann die Item-Liste mit Any()

warum would Wenn Sie das gewünschte Ergebnis mit einer einzelnen LINQ to Entities-Abfrage erhalten möchten:

0

Versuchen Sie Folgendes:

public List<Item> GetItemsByAccountCode(string code) 
{ 
    List<Item> itemList = new List<Item>(); 
    using(DbEntities context = new DbEntities()) 
    { 
     // Get the list of items codes of a specific supplier 
     var itemCodes = context.ItemSupplier 
           .Where(p => p.AccountCode == code) 
           .Select(p => p.ItemCode) 
           .ToList(); 

     // Get al the items based on the itemSupList 
     // Below is not working 
     itemList = context.Item.Where(p => itemCodes.Contains(p.ItemCode)); 
    } 
} 
Verwandte Themen