views:

17

answers:

1

Hi!

I have the following code in Linq to Entity:

var policy= from pol in conn.Policy
            where pol.Product.DESCRIPTION=="someProduct"
            SELECT pol;

Then, the table Policy, has some dependencies for a table called Entity. If I do this:

foreach(Policy p in policy){
    if(!p.Entity.IsLoaded) p.Entity.Load();
    IEnumerable<Entity> entities= from ent in p.Entity
                                  Where ent.EntityType.DESCRIPTION=="SomeEntityType"
                                  select ent;
    Console.Writeline(entities.ElementAt(0).NAME);
}

It says, "Object not set to an instance", but if I do:

foreach(Policy p in policy){
    if(!p.Entity.IsLoaded) p.Entity.Load();

    foreach(Entity et in p.Entity)Console.Write(et.NAME);

}

It works! Can anyone tell me why?

Thank you, Best regards.

A: 

I'd say it's because your LINQ statement isn't returning any values, so entities is null.

Your second example works because you're not trying to filter the results.

Do you have some entities that have the DESCRIPTION set to exactly the string (including case)?

ChrisF