softshipper
softshipper

Reputation: 34061

Can not read data via linq from ef

I have two related models and want to read via linq

using (var ctx = new TextsContext())
{
    var data = from e in ctx.Text
               where e.LanguageCode == lang
               select e;

    foreach (var d in data)
    {
        Debug.WriteLine(d.Language, d.Fieldname);
    }
}

First model

public class Language
{
    public string Code { get; set; }
    public string Country { get; set; }
}

Second model

public class Text
{
    public string Fieldname { get; set; }
    public string LanguageCode { get; set; } // Add this foriegn key property
    public string Description { get; set; }

    // Navigation properties
    public virtual Language Language { get; set; }
}

I am using code first(Fluent API) to build relationship between the two tables. When I want to query with linq, I've got error message:

There is already an open DataReader associated with this Command which must be closed first.

Upvotes: 2

Views: 43

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

I assume that if you do a the Include() and ToList() it will solve it. Probably because of the lazy loading of linq while it iterates it creates another reader in order to get the other entity (Language).

using (var ctx = new TextsContext())
{
    var data = (from e in ctx.Text.Include("Language")
               where e.LanguageCode == lang
               select e).ToList();

    foreach (var d in data)
    {
        Debug.WriteLine(d.Language, d.Fieldname);
    }
}

Upvotes: 2

Related Questions