How do you add extra property using join

65 views Asked by At

If I have an entity:

class Post
{
    [ Key ]
    public int PostID { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public string Comment { get; set; }
    public virtual Project Project { get; set; }
    ...

    public bool LikedByUser; // Append this property
}

public class PostLike
{
    public int PostLikeID { get; set; }
    public virtual Post Post { get; set; }
}

Is there a way I can do a join on a call to the database and just append this last property (mentioned in the code) as an extra... for example, this code is stupid (and probably doesn't work):

this.context.Posts
    .Join( 
        this.context.PostLikes,
        p => p.PostID,
        pl => pl.Post.PostID,
        // This is the bit that can't be right!
        ( p, pl ) => new Post()
        {
            PostID = p.PostID,
            Title = p.Title,
            Body = p.Body,
            Comment = p.Comment
            Project = p.Project,
            LikedByUser = pl.Count > 0 ? true : false
        }
    );

I would like something like this:

this.context.Posts
    .Join( 
        this.context.PostLikes,
        p => p.PostID,
        pl => pl.Post.PostID,
        ( p, pl ) => {
            p.LikedByUser = pl.Count > 0 ? true : false;
        }
    );
1

There are 1 answers

2
Dave Bish On

So - one way you could do this, is via a sub-query:

var posts = this.context.Posts
    .Select(p =>
    new Post()
    {
        PostID = p.PostID,
        Title = p.Title,
        Body = p.Body,
        Comment = p.Comment
        Project = p.Project,
        LikedByUser = this.context.PostLikes.Any(pl => pl.PostId = p.PostID)
    });

If that property isn't part of the existing class - you could project into an anonymous type, for use:

var posts = this.context.Posts
    .Select(p =>
    new {
        Post = p,
        LikedByUser = this.context.PostLikes.Any(pl => pl.PostId = p.PostID)
    });