2012-02-23 83 views
1

我使用LINQ在我的項目,以SQL表的字段。 我有兩個表類別和工件與分類和工件之間的一對多關係。在CatgID的基礎上,我試圖刪除工件。我寫的查詢檢查是否有任何工件存在id的外鍵,然後我將Artifact ID分組到g以便進行計數,以便我可以創建條件以將Artifact ID作爲參數傳遞給將刪除的函數Artifacts表中的所有內容。無法訪問使用範圍變量中的LINQ to SQL

我不能使用相同的範圍變量「a」來選擇artid的數據類型。爲什麼不?我如何做到這一點或以其他方式實現我想要的?

public static void DeleteCategory(int id) 
{ 
    var result = from a in adb.Artifacts 
        where a.CatgId == id 
        group a by a.ArtId into g 
        select new { count = g.Count(), **artid = a.ArtId** }; //not able to get ArtId using range variable a. 

    if (result.count > 0) 
    { 
     foreach (var r in result) 
     { 
      MyArtifact.DeleteByKey(r.artid); 
     } 
    } 
} 

回答

2

您可以只使用g.ArtId因爲你的artid的數據類型組:

public static void DeleteCategory(int id) 
{ 
    var result = from a in adb.Artifacts 
       where a.CatgId == id 
       group a by a.ArtId into g 
       select new { count = g.Count(), artid = g.Key }; //not able to get ArtId using range variable a. 

    if (result.count > 0) 
    { 
     foreach (var r in result) 
     { 
      MyArtifact.DeleteByKey(r.artid); 
     } 
    } 
} 
+0

嘿HCB, 我一直在使用範圍變量g和訪問神器表的artid的數據類型嘗試。但是,當我做到這一點,我面對這個錯誤 「‘System.Linq.IGrouping ’不包含關於‘artid的數據類型’和沒有擴展方法‘artid的數據類型’接受型的第一參數'的定義System.Linq.IGrouping 」可以找到(是否缺少using指令或程序集引用?)」 – 2012-02-23 11:56:21

+0

您可以使用g.First()。artid的數據類型。我認爲這應該工作(我也會編輯答案) – hcb 2012-02-23 12:01:47

+0

是的這個工程,但我不能理解使用First()的概念。它說First()返回序列的第一個元素! – 2012-02-23 12:04:19