2017-06-29 10 views
0

別のLINQクエリのパラメータとして使用するLINQクエリの結果を格納するvar型があります。別のLINQクエリを呼び出すために変数としてLINQクエリを保存する

私はコントローラのために使用しています:

public async Task<ActionResult> Index(String aContainer) 
    { 
     var partsLocations = db.PartsLocations.Include(p => p.LocationType).Include(p => p.ManufacturingPlant); 
     var empty = from y in db.PartsLocations select y; 

        if (!String.IsNullOrEmpty(aContainer)) 
        {    
         var parentLoc = from a in db.PartsLocations 
            where a.LocationName.Contains(aContainer) 
            select a.ParentLocation; 
         var location = (from b in db.PartsLocations.Where(b => parentLoc.Equals(b.LocationID)) 
            select b).ToList();        

         return View(location.ToList()); 
        } 
     empty = empty.Where(r => r.LocationName.Contains(null)); 
     return View(await empty.ToListAsync()); 
    } 

私のビューは次のとおりです。

@model IEnumerable<Parts.PartsLocation> 

@{ 
    ViewBag.Title = "Index"; 
} 

モデル:

public int LocationID { get; set; } 
    public int TypeID { get; set; } 
    public string LocationName { get; set; } 
    public string Description { get; set; } 
    public int PlantID { get; set; } 
    public Nullable<int> BayID { get; set; } 
    public Nullable<int> SecurityGroupID { get; set; } 
    public Nullable<int> ParentLocation { get; set; } 
    public Nullable<System.DateTime> LastMoved { get; set; } 
    public string Notes { get; set; } 

しかし、私はエラーが取得しています:「タイプ」をキャストすることができませんがSystem.Int32 '' System.Object 'を入力します。LINQ to Entitiesは、EDMプリミティブまたは列挙型のキャストのみサポートしています。 SQLで

私のような何かを実行します。PartsLocationsにLocationName = 'aContainerに' FROM

SELECT ParentLocationを。

SELECT * FROM PartsLocations where LocationID = ParentLocation;

LINQクエリの結果を別のクエリのパラメータとして使用するにはどうすればよいですか。 ありがとうございます!

答えて

0

この

   var parentLoc = from a in db.PartsLocations 
          where a.LocationName.Contains(aContainer) 
          select a.ParentLocation; 

は結果ではありません。これはクエリです。

あなたは結果をしたい場合は、クエリを実行します。

var location = parentLoc.Single(); 

試してみてください、のようなもの:私が正しくあなたを理解していれば

   var parentLoc = (from a in db.PartsLocations 
           where a.LocationName == aContainer 
           select a.ParentLocation).Single(); 

       var locations = (from b in db.PartsLocations 
           where b.LocationID == parentLoc 
           select b).ToList(); 
+0

私は2番目のクエリを置き換える「)するvar場所= parentLoc.Single(;」辞書に渡されたモデルアイテムは 'System.Int32'タイプですが、この辞書は 'System.Collections.Generic.IEnumerable'1のモデルアイテムを必要とします[Parts.PartsLocation] ' –

+0

@ David Browne-実際には、パラメータとしてparentLocを使用して、2番目のLINQクエリで返されるレコードセットが必要です。 –

+0

例の編集を参照してください。 –

0

は、あなたが親の場所としてparentlocを持つ場所を探しています。親ロケーションを参照するナビゲーションプロパティーPartsLocation.ParentLocationを使用すると、簡単にそれを実行できます。あなたは、そのプロパティを追加し、ParentLocationIdに現在ParentLocationプロパティの名前を変更することができるはずです。

var location = (from b in db.PartsLocations 
       where b.ParentLocation.LocationName.Contains(aContainer) 
       select b).ToList();        
関連する問題