sreddy
sreddy

Reputation: 200

Many-to-many relationship, edmx, Entity Framework, SQL express DB

I have a question regarding many-to-many relationships in regards to entity framework.

Ok, so I have an existing SQL express db which I have extended to included a new table called "Country". Since I want to have a many to many relationship between "Country" and another table "Language" I have made an intersection table. So far so good.

I have a VS project with and edmx-file which I have updated from the new db. The diagram looks ok, I can see a many to many relationship between Country and Language. I can't see the intersection table between Country and Language (but this is a feature according to Google).

I have manually filled out the Country and intersection table in SQL Server Management Studio.

As I have understood many-to-many relationships in Entity Framework I should be able to simply get languages associated to a country by writing: country.Language . Here is the specific code:

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

No languages are returned .. I have double checked that I have typed the correct values in the intersection table, am I missing something?

Upvotes: 1

Views: 656

Answers (1)

Fabiano
Fabiano

Reputation: 5194

Is LazyLoading enabled? (Open the edmx file and in the properties windows set "Lazy Loading Enabled" to true.

Or edit the edmx with the xml editor

<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">

Or enable it programatically:

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

Or eager load the Language:

context.Country.Include("Language")

Upvotes: 1

Related Questions