简体   繁体   中英

Entity Framework query with sub select

I have a scenario where I have 3 tables:

  • News [Id, Name]

  • Users [Id, Name]

  • Likes [Id, News, User]

I am trying to write a query that will return all news as well as a column that returns true or false (if the a specific user has or not liked a content).

On SQL I would to something like this:

select *, 
(select top 1 id from newslike nl where nl.newsid = n.id and nl.userid = 1) 
from News n

How can I achieve that with an EF query?

I already add to my class a NotMapped property for this boolean value


Edit:

public partial class News
{
    public int Id { get; set; }       

    public virtual ICollection<NewsLike> NewsLike { get; set; }
    [NotMapped]
    public bool LikedByCurrentUser { get; set; }
}


public partial class NewsLike
{
    public int Id { get; set; }
    public int NewsId { get; set; }
    public int UserId { get; set; }

    public virtual News News { get; set; }
    public virtual User User { get; set; }
}
News.Where(n => n.Likes.Any(l => l.UserId == userId));

Here userId is the ID of a desired user. You'll get all news that the user liked.

Assuming there's a navigation property from News to `Likes:

db.News.Select(
    n => new {n.Id, n.Name, UserLikes = n.Likes.Any(l => l.userid == 1))}
    );

Since I have a not mapped property to store the bool value if the user has liked the content, can my query returns a list of news instead of the anonymous type?

Sure, just create a new News item instead of an anonymous type:

db.News.Select(
    n => new News {
        Id = n.Id,
        Name = n.Name, 
        LikedByCurrentUser = n.NewsLike.Any(l => l.userid == currentUser))}
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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