开发者

ADO.NET Navigation Properties

I'm having a little problem using Navigation properties and inheritance on ADO.NET.

This is my Data Model:

ADO.NET Navigation Properties

First, some vocabulary:

Categoria = Category

Formulario = Form

Campo = Field

Imagem = Image

Paragrafo = Paragraph

Escolha = Choice

Texto = Text

Resposta = Answer

So, I'm trying to create a custom property on a Form returning it's answers count.

The normal approach (i think) would be:

public partial class Formulario
{
    public int Respostas
    {
        get
        {
            List<Item> itens = this.Itens.ToList();

            IEnumerable<Campo> campos = from m in itens where m as Campo != null select (Campo)m;
            int soma = campos.Sum(m => m.Respostas.Count);

            return soma;
        }
    }
}

But it doesn't work. The itens list returns 0 elements. But when I do as below, it return the 4 items it should:

public partial class Formulario
{
    public int Respostas
    {
        get
        {
            FormulariosDB db = new FormulariosDB();

            List<Item> itens = db.Items.Where(m => m.Formulario.Id == this.Id).ToList();

            IEnumerable<Campo> campos = from m in itens where m as Campo != null select (Campo)m;
            int soma = campos.Sum(m => m.Respostas.Count);

            return soma;
        }
    }
}

It only works when I instanciate the开发者_运维知识库 entire data model. Does anyone knows why?

PS: I'm using the .toList() method so I can use all Linq queries, not only the ones Linq2Entities allows me to


I'm guessing you're either using Entity Framework 1 or you don't have lazy loading enabled in Entity Framework 4.

In your class, you're expecting the Itens collection to be loaded. This isn't always the case as the collection will only be loaded if it was explicitly eager loaded when the Formulario object was retrieved from the database.

You need to add two lines of code and everything should be good to go:

if(!Itens.IsLoaded)
    Itens.Load();

List<Item> itens = Itens.ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜