2011-03-16 125 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