【问题标题】:How to query with a join with linq to sql如何使用 linq to sql 进行连接查询
【发布时间】:2014-05-29 17:38:32
【问题描述】:

我正在尝试从我的类别表中查询给定术语的礼物。 Entity Framework 创建了一个桥接表来连接我的“Gift”和“GiftCategroies”。但是我的查询没有结果。

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

这是我的查询,试图获取给定giftcategory 项的礼物。没有返回结果。我不确定是否需要加入此类查询。

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;

【问题讨论】:

    标签: c# entity-framework ef-code-first linq-to-entities


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      相关资源
      最近更新 更多