C # Entity Framework populates partial property

I have an object called Person that has a collection of addresses.

I created:

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

This returns an error:

The ObjectContext instance has been deleted 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; } } } 
+4
source share
1 answer

I found that this works to load the "count" property without loading all the objects 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 disadvantage, of course, is that the AddressCount needs to be configured. I think you could give it an internal setter if your context is in the same assembly as the entity class.

You may not need Include("Addresses") , which is worth checking out. The change has been deleted, as it is not necessary (and may make the request work more than necessary).

+4
source

Source: https://habr.com/ru/post/1337879/


All Articles