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

c# entity-framework-6 join

Question

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". 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.

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.

I'm finding the best and easy way to fill this property.

1
2
1/20/2018 6:41:55 AM

Accepted Answer

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:

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();
5
1/20/2018 9:13:14 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow