【问题标题】:traversing one to many relationships in entity framework遍历实体框架中的一对多关系
【发布时间】:2013-03-02 19:19:43
【问题描述】:

我无法弄清楚如何在使用 EF 5 的 asp.net 站点中使用 LINQ-To-SQL 遍历一对多关系。我已经在类文件中建立了关系,但是当我尝试从在我的 where 子句中,父到子没有给出要过滤的子列的列表。谁能告诉我我的代码有什么问题,我是 EF 和 LINQ 的新手。

产品.cs:

    public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Category Category { get; set; }
}

}

Category.cs:

    public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual IList<Product> Products { get; set; }
}

代码隐藏:

            using (var db = new Compleate())
        {
            rpBooks.DataSource = (from c in db.Categories
                                  where c.Products.Name == "Books"
                                  select new
                                  {
                                      c.Name
                                  }).ToList();
        }

【问题讨论】:

    标签: c# linq-to-sql webforms entity-framework-5 asp.net-4.5


    【解决方案1】:

    您想要图书类别中的所有产品吗?

    from p in db.Products
    where p.Category.Name == "Books"
    select new
    {
        p.Name
    }
    

    或者您是否希望所有类别都包含称为书籍的产品?

    from c in db.Categories
    where c.Products.Contains( p => p.Name == "Books")
    select new
    {
        c.Name
    }
    

    顺便说一句,如果你只选择名字,你可以跳过选择部分的匿名类型...

    select p.name
    

    【讨论】:

    • 谢谢,我在代码中做了一些反话。您的第一个代码集使其按预期工作。
    【解决方案2】:

    好的,我必须将代码隐藏更新为:

                using (var db = new Compleate())
            {
               rpBooks.DataSource = (from c in db.Categories
                                  join p in db.Products on c.ID equals p.id
                                  where c.Products.Name == "Books"
                                  select new
                                  {
                                      c.Name
                                  }).ToList();
    
            }
    

    【讨论】:

      【解决方案3】:

      应该是name = c.Name 这不是遍历的问题,而是语法的问题,请在此处阅读brief article on anonymous types

      【讨论】:

      • name = c.Name 无效,我正在尝试根据产品名称进行过滤(在此示例中)。
      猜你喜欢
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 2017-06-27
      • 2017-01-28
      • 2011-12-17
      相关资源
      最近更新 更多