2011-11-07 112 views
1

我有一个关于实体框架的多对多关系的问题。多对多的关系,EDMX,实体框架,SQL Express数据库

好的,所以我有一个现有的SQL Express数据库,我已经扩展到包括一个名为“国家”的新表。因为我想在“国家”和另一个表“语言”之间有多对多的关系,所以我制作了一张交叉表。到现在为止还挺好。

我有一个VS项目和我已经从新的数据库更新的EDMX文件。图表看起来不错,我可以看到国家和语言之间的多对多关系。我无法看到国家和语言之间的交集表(但根据Google,这是一项功能)。

我已经手动填写了SQL Server Management Studio中的国家和交叉表。

正如我已经理解实体框架中的多对多关系,我应该能够通过编写country.Language简单地获取与一个国家相关的语言。下面是具体的代码:

string code = "fi"; 

     using (var context = new FooEntities()) 
     { 
      IQueryable<Country> countriesTest = context.Country; 
      IQueryable<Country> countries = context.Country.Where(s => s.CountryCode == code); 
      Country country = countries.First(); //this works, I get the correct Country 
      EntityCollection<Language> languages = country.Language; //this does not work, collection is empty 

没有语言返回。我有双重检查,我在路口表中键入正确的价值观,我失去的东西吗?

回答

1

是否启用LazyLoading? (打开EDMX文件,并在属性窗口设置“延迟加载启用”真

或者用XML编辑器编辑EDMX

<edmx:ConceptualModels> 
    <Schema Namespace="FooModel" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm"> 
     <EntityContainer Name="FooEntities" annotation:LazyLoadingEnabled="true"> 

或者编程启用它。

using (var context = new FooEntities()) 
{ 
    context.ContextOptions.LazyLoadingEnabled = true; 
    IQueryable<Country> countriesTest = context.Country; 

或渴望加载语言:

context.Country.Include("Language") 
+0

好问题。我没有看到延迟加载启用在我的属性窗口中,我有A连接类别和模式类别。我应该把context.ContextOptions.LazyLoadingEnabled = true;在Designer.cs文件中 - 如果是的话,在哪里? – sreddy

+0

除了模式和连接类别之外,我还有代码生成和数据库脚本生成。查看更新的答案 – Fabiano