Eric Andres
Eric Andres

Reputation: 3417

Adding a property for the count of associated entities in Entity Framework Code First

I'm using Code First to write my data layer, then transmitting to a Silverlight front end using RIA services. Since I have to serialize everything, I would like to get some additional information on each entity before sending it across the wire (to reduce load time). In the past I have done this by translating everything to a POCO class that has the additional information. I'm wondering if there's a better way of doing this. To give you an idea, here's my class:

public class District
{
    // ... Other properties, not important
    public ICollection Installations { get; set; }

    //The property I would like to calculate on the fly
    [NotMapped]
    public int InstallationCount { get; set; }
}

Is there a way to have this property calculate automatically before I send it across the wire? One option would be just to Include the Installation collection, but that adds a lot of bulk (there are about 50 properties on the Installation entity, and potentially hundreds of records per district).

Upvotes: 3

Views: 216

Answers (1)

gbabiars
gbabiars

Reputation: 575

Rather than making InstallationCount an automatic property, just use the get to return the count function of Installations collection.

public class District
{
    public virtual ICollection<Installation> Installations { get; set; }

    [NotMapped]
    public int InstallationCount { get { return Installations.Count; } }
}

Upvotes: 1

Related Questions