开发者

C# Entity Framework populate partial property

开发者 https://www.devze.com 2023-02-07 15:30 出处:网络
I have an entity called Person who has a collection o开发者_StackOverflow社区f addresses. I created:

I have an entity called Person who has a collection o开发者_StackOverflow社区f 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;
                }
            }
        }


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).

0

精彩评论

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

关注公众号