如何在Entity数据库调用上映射额外的附加属性

时间:2015-04-10 13:02:31

标签: c# linq entity-framework

我有以下课程:

public class MessageThread
{
    /// <summary>
    /// Messages can relate to messages through replies
    /// </summary>
    public virtual List<Message> Messages { get; set; }

    [NotMapped]
    public int CountUnreadMessages {get;set;}
}

在我的存储库中,我得到一个MessageThread列表,如下所示:

return this.PrepareAllMessageThreadsQuery( page, amount, sort, order, searchCriteria )
    .Where(x => x.SentTo.Id == userID)
    .Skip((page - 1) * amount)
    .Take(amount);

我想填写CountUnreadMessages部分以及...我该如何做...我认为它看起来像这样:

return this.PrepareAllMessageThreadsQuery( page, amount, sort, order, searchCriteria )
    .Where(x => x.SentTo.Id == userID)
    .Select(x => {
        x.UnreadMessageCount = x.Messages.Where(a => a.Read == false).Count();
    })        
    .Skip((page - 1) * amount)
    .Take(amount);

显然以上情况不起作用:)

我该怎么做?

我意识到可能有这样的选项(虽然我无法让它工作):

return this.PrepareAllMessageThreadsQuery( page, amount, sort, order, searchCriteria )
    .Where(x => x.SentTo.Id == userID)
    .Select(x => new MessageThread() {
        // Lots of other properties have to be mapped too :(
        UnreadMessageCount = x.Messages.Where(a => a.Read == false).Count()
    })        
    .Skip((page - 1) * amount)
    .Take(amount);

但是为了它,我必须重新映射整个班级......

修改......

我已经离开了:

public class MessageThread
{
    /// <summary>
    /// Messages can relate to messages through replies
    /// </summary>
    public virtual IList<Message> Messages { get; set; }

    [NotMapped]
    public int UnreadMessageCount
    {
        get
        {
            if( this.Messages == null )
            {
                return 0;
            }

            return this.Messages.Where(x => x.Read == false).Count();
        }
    }
}

这现在看起来不错吗?

1 个答案:

答案 0 :(得分:1)

您可以将UnreadMessageCount设为get-only属性。这仅在Messages加载对象时才有效。

[NotMapped]
public int CountUnreadMessages 
{
    get
    {
        return Messages.Count(x => !x.Read);
    }
}