如何使用join添加额外的属性

时间:2015-06-08 13:07:59

标签: c# entity-framework join

如果我有实体:

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

有没有办法可以在调用数据库时进行连接,只需将最后一个属性(在代码中提到)附加为额外的...例如,这段代码是愚蠢的(可能并不是...工作):

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

我想要这样的事情:

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

1 个答案:

答案 0 :(得分:0)

所以 - 你可以这样做的一种方法是通过子查询:

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

如果该属性不是现有类的一部分 - 您可以投射到匿名类型,以供使用:

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