繁体   English   中英

如何使用linq to sql进行联接查询

[英]How to query with a join with linq to sql

我正在尝试从类别表中查询给定期限的礼物。 实体框架创建了一个桥接表,以将我的“礼物”与“我的礼物类别”连接起来。 但是查询我没有结果。

从DbContext:

public DbSet<Gift> Gifts { get; set; }
public DbSet<GiftCategory> Categories { get; set; } 

我创建的两个实体:

public class Gift
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<GiftCategory> Categories { get; set; }
    public int Rating { get; set; }
}

public class GiftCategory
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public ICollection<Gift> Gifts { get; set; }
}

这是我的查询,用于尝试获取给定的礼物类别术语的礼物。 没有返回结果。 我不确定这种查询是否需要联接。

var model =
    from gifts in db.Gifts
    join giftCategory in db.Categories on gifts.Id equals giftCategory.Id
    where giftCategory.Name.Contains(searchTerm)
    select gifts;

您应该使用导航属性而不是联接:

var gifts = (from c in db.Categories
             from g in c.Gifts
             where c.Name.Contains(searchTerm)
             select g).Distinct().ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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