简体   繁体   English

在Entity Framework Code First中添加关联实体计数的属性

[英]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. 我正在使用Code First编写我的数据层,然后使用RIA服务传输到Silverlight前端。 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. 在过去,我通过将所有内容翻译成具有附加信息的POCO类来完成此操作。 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). 一种选择只是包含安装集合,但这会增加大量的批量(安装实体上有大约50个属性,每个区域可能有数百个记录)。

Rather than making InstallationCount an automatic property, just use the get to return the count function of Installations collection. 而不是使InstallationCount成为自动属性,只需使用get返回Installations集合的count函数。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM