简体   繁体   English

实体框架如何填充需要联接的NotMapped属性?

[英]Entity Framework How to fill NotMapped Property that need a join?

I have a PostInfo table and LikeInfo Table,PostInfo have list of LikeInfo (for post likes).PostInfo table have a NotMapped property named of "LikeCount". 我有一个PostInfo表和LikeInfo表,PostInfo有LikeInfo列表(用于帖子点赞)。PostInfo表具有一个名为“ LikeCount”的NotMapped属性。 I want select list of PostInfoes and join to LikeInfo table and calcualte count of LikeInfoes of post and fill count of this to LikeCount property. 我想要选择PostInfoes的列表,并加入LikeInfo表,然后发布LikeInfoes的计算数量,并将其填充到LikeCount属性。

Here is my sample: 这是我的示例:

        var query = context.PostInfoes.Where(x => x.UserId == userId).Include(x => x.LikeInfoes);
        foreach (var item in query)
        {
            item.LikeCount = item.LikeInfoes.Count;
        }
        return query.ToList();

That is not good way for me because I do foreach on query and set LikeCount manualy however I dont want/need include full peoperties of LikeInfo table in this case . 这对我来说不是一个好方法,因为我会在查询中进行foreach并手动设置LikeCount, 但是在这种情况下,我不希望/不需要包括LikeInfo表的全部功能

I'm finding the best and easy way to fill this property. 我正在寻找填充此属性的最佳简便方法。

Since EF6 does not allow projecting to entity type, you need to use LINQ to Entities query with intermediate anonymous type projection containing all necessary data, then switch to LINQ to Objects (via AsEnumerable() ) and do the final projection, using a delegate block to perform the necessary unmapped property fixups: 由于EF6不允许投影到实体类型,因此您需要对包含所有必要数据的中间匿名类型投影使用LINQ to Entities查询,然后切换到LINQ to Objects(通过AsEnumerable() )并使用委托块进行最终投影执行必要的未映射属性修复:

var result = context.PostInfoes
    .Where(x => x.UserId == userId)
    .Select(x => new { Info = x, LikeCount = x.LikeInfoes.Count() })
    .AsEnumerable()
    .Select(x =>
    {
        x.Info.LikeCount = x.LikeCount;
        return x.Info;
    })
    .ToList();

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

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