如何在我的LINQ查询中包含第二个表中的列

时间:2019-01-13 06:28:17

标签: c# entity-framework linq-to-sql entity-framework-6

我有一个名为Ad(广告)的表:

public class Ad
{
    public long AdId { get; set; }
    public long UserId { get; set; } // <-- this is advertiser not currentUser
    public string Description { get; set; }
}

用户可以在其收藏夹列表中添加零个或多个广告,因此我创建了另一个名为Favourite的表:

public class Favourite
{
    public long FavouriteId { get; set; }
    public long AdId { get; set; }
    public long UserId { get; set; }
}

我有一个名为User的表:

public class User
{
    public long UserId { get; set; }
    public string Name { get; set; }
}

在给定currentUserIdadId的情况下,这就是我检索广告的方式:

public TEntity GetAd(long currentUser, long adId)
{
    return Context.Ad
        .Where(r.AdId == adId)
        // include a flag indicating the pair (adId and currentUserId) exist in Favouries table
        .FirstOrDefault();
}

我想在结果中包含一个标志,指示是否将广告添加到收藏夹列表中?

2 个答案:

答案 0 :(得分:2)

在Entity Framework中,我们具有导航属性。您可以在子表上为父表行定义导航属性。对于您而言,您可以按以下方式更改子实体:

public class Favourite
{
    public long FavouriteId { get; set; }
    public long AdId { get; set; }
    public long UserId { get; set; }

    public virtual Ad Ad { get; set; }
}

,现在实体框架应该为您填充它,您可以像这样访问Ad的{​​{1}}相关行:

Favourite

但就您而言,您可以编写查询以了解广告是否受到喜爱:

return Context.Ad
        .Where(r => r.UserId == userId && r.AdId == adId)
        .Select(x => x.Ad.Description);

您可以创建一个域视图模型并将其映射到该模型:

return Context.Ad
        .Where(r.AdId == adId)
        Select(x => new 
                   { 
                      ad = x, 
                      IsFavourite = Context.Favourite.Any(y=> y.AdId = adId 
                                                    && y.UserId = currentUserid))
        .FirstOrDefault();

并填充它:

public UserFavouriteAd
{
    public Ad Ad { get; set; }
    public IsFavourite { get; set; }
}

答案 1 :(得分:0)

public object GetAd(long currentUser, long adId)
{
    return from a in Context.Favourite
           where a.UserId  == currentUser
           select new {
                      flag = a.AdId != null
                      a.FavouriteId,
                      //etc
                      };
}