我在使用EF 5的asp.net网站中使用LINQ-To-SQL找出如何遍历一对多关系时遇到了麻烦。我已经在类文件中建立了关系但是当我尝试从我的where子句中的父对象我没有给出要筛选的子列的列表。任何人都可以告诉我我的代码有什么问题,我是EF和LINQ的新手。
Product.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();
}
答案 0 :(得分: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
答案 1 :(得分:0)
好的,我必须更新后面的代码,如下所示:
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();
}
答案 2 :(得分:-1)
它应该是name = c.Name
这不是遍历的问题,这是语法问题,请在此处阅读brief article on anonymous types