4

I have an entity called Person who has a collection of addresses.

I created:

public partial class Person
{
     public int AddressCount{get{return Addresses.Count;}}
}

This returns the error:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

I am returning a collection of people, how can I do this without doing this:

public int AddressCount
        {
            get
            {
                using (var c = new Entities())
                {
                    return c.People.Where(s => s.PersonId == PersonId).Single().Addresses.Count;
                }
            }
        }
1
  • Why don't you want to do 'this' ? Commented Feb 1, 2011 at 0:44

1 Answer 1

4

I've found that this works to eager-load a "count" property without loading all the entities in the collection:

using (var context = new Entities())
{
    var people = (from p in c.People
                  select new 
                  {
                      Person = p,
                      AddressCount = p.Addresses.Count
                  }).ToList();

    foreach (var item in people)
    {
        item.Person.AddressCount = item.AddressCount;
    }
}

The drawback, of course, is that AddressCount needs to be settable. I guess you could give it an internal setter if your context is in the same assembly as the entity class.

You may not need the Include("Addresses") on there - that's worth testing. Edit removed it since it's not necssary (and may in fact make the query do more work than it has to).

Sign up to request clarification or add additional context in comments.

3 Comments

beat me by about 15 seconds.. +1
@RPM1984 Do you remember if the Include() call is necessary?
since your projecting (to an anonymous type), no - it's not necessary, EF will get what it needs automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.