在“实体框架代码优先”中添加关联实体计数的属性

本文关键字:实体 关联 添加 属性 框架 代码 | 更新日期: 2023-09-27 18:10:48

我使用Code First来编写我的数据层,然后使用RIA服务传输到Silverlight前端。由于我必须序列化所有内容,因此我希望在通过网络发送每个实体之前获得有关其的一些附加信息(以减少加载时间)。在过去,我通过将所有内容转换为具有附加信息的POCO类来实现这一点。我在想有没有更好的办法。为了给你一个概念,下面是我的类:

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; }
}

是否有一种方法可以在我发送它之前自动计算这个属性?一种选择是只包含Installation集合,但这会增加很多批量(Installation实体上大约有50个属性,每个区域可能有数百条记录)。

在“实体框架代码优先”中添加关联实体计数的属性

与其让InstallationCount成为一个自动属性,不如使用get返回installation集合的计数函数。

public class District
{
    public virtual ICollection<Installation> Installations { get; set; }
    [NotMapped]
    public int InstallationCount { get { return Installations.Count; } }
}