2011-03-16 146 views
0

我有一個組織表結構如下比較外鍵的實體框架3.5

[dbo].[Organizations](
[Id] [int] IDENTITY(1,1) NOT NULL, 
[Name] [nvarchar](50) NOT NULL, 
[Phone] [nvarchar](13) NULL, 
[Fax] [nchar](11) NULL, 
[Address] [nvarchar](100) NULL, 
[URL] [varchar](50) NULL, 
[Email] [nvarchar](50) NULL, 
[EstablishedYear] [nchar](4) NULL, 
[CategoryId] [int] NULL, 
[RegionId] [int] NULL, 
[CityId] [int] NULL, 
[ProvinceId] [int] NULL, 
[CountryId] [int] NULL, 
[ImageFileName] [nvarchar](50) NULL) 

因爲我使用實體框架3.5, 我已經使用部分類添加外鍵屬性(countryid ,provinceid,...)

public partial class Organization 
{ 
    public int? CountryId 
    { 
     get 
     { 
      if (CountryReference.EntityKey == null) 
       return null; 
      return (int)CountryReference.EntityKey.EntityKeyValues[0].Value; 
     } 
     set 
     { 
      if (value != null && value != -1) 
       CountryReference.EntityKey = new EntityKey("Entities.Countries", "CountryId", value); 
      else 
       CountryReference.EntityKey = null; 
     } 
    } 

}

現在我有一個查詢,但它拋出一個異常:

查詢:

if (Enumerable.Any(ctx.Organizations.Where(s => s.CountryId== Organization.CountryId && s.ProvinceId == Organization.ProvinceId && s.CityId == Organization.CityId && s.Name == Organization.Name))) 

例外:

The specified type member 'CountryId' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. 

我只是想比較導航屬性,任何想法?

回答

-1

我找到了解決方案:

if (Enumerable.Any(ctx.Organizations.AsEnumerable(). 
     Where(s => s.CountryId == Organization.CountryId && 
        s.ProvinceId == Organization.ProvinceId && 
        s.CityId == Organization.CityId && 
        s.Name == Organization.Name))) 

befor使用其中條件我用AsEnumerable()方法。

+0

-1這將從您的數據庫中加載您的* ENTIRE *'Organizations'表 - @Ladislav Mrnka的解決方案是正確的。 – 2011-03-18 16:17:20

2

您不能在linq-to-entities查詢中使用部分類中定義的屬性。必須直接使用導航屬性:

ctx.Organizations.Where(o => o.Country.Id == someCountryId); 
+0

坦克爲您的答覆,有時,國家是空的,我應該檢查它之前訪問country.id,這是很多的編碼,有沒有更好的解決方案? – 2011-03-16 12:33:42

+0

你不需要在linq-to-entities查詢中檢查它。 – 2011-03-16 12:40:18

+0

當國家爲空時拋出空引用異常 – 2011-03-16 12:46:03