【发布时间】:2018-10-21 22:28:24
【问题描述】:
我在 ASP.NET EF 应用程序中有两个具有多对多关系的类。我正在尝试查找所有Listings,其中包含从视图发布的任何Categories。类别是视图表单上的复选框。
这些是具有简化导航属性的类,例如:
public class Listing
{
public int ID { get; set; }
public ICollection<Category> Categories { get; set; }
...
}
public class Category
{
public int ID { get; set; }
public ICollection<Listing> Listings { get; set; }
...
}
// this is the join table created by EF code first for reference
public class CategoryListings
{
public int Category_ID { get; set; }
public int Listing_ID { get; set; }
}
这是我试图在我的 MVC Controller 中使用的查询,但它不起作用,我真的不知道还能尝试什么:
if (model.Categories !=null && model.Categories.Any(d => d.Enabled))
{
List<Listing> itemsSelected = null;
foreach (var category in model.Categories.Where(d => d.Enabled))
{
var itemsTemp = items.Select(x => x.Categories.Where(d => d.ID == category.ID));
foreach (var item1 in itemsTemp)
{
itemsSelected.Add((Listing)item1); //casting error here
}
}
items = itemsSelected;
}
在 SQL 中,我会使用子查询(子查询代表可以搜索的多个类别)来编写:
select l.id, cl.Category_ID
from
listings as l inner join CategoryListings as cl
on l.id=cl.Listing_ID
inner join Categories as c on c.ID = cl.Category_ID
where c.id in (select id from Categories where id =1 or id=3)
如何使用导航器或 lambda 在 EF 中编写该 SQL 查询? SQL 中的子查询将更改每次搜索,并且可以是任何 id 或 ID。
【问题讨论】:
-
你试过嵌套
Anys吗?类似Listing.Categories.Any(x => listIds.Any(y => x.Id = y)).. -
@BagusTesa 我用
var selectedItems = listings.Any(x => model.Categories.Any(y => x.ID == y.ID));试过这个,它只返回true。我需要一组列表实体,我该如何获得? -
啊,snap,应该是
Listing.Categories.Where(x => listIds.Any(y => x.Id = y))我不应该在没有完全清醒的时候写建议。请注意listIds是您想要获得的类别ID 的List。listIds.Any(y => x.Id == y)将转换为x.id in (select id from Categories where id =1 or id=3)。 -
也许我没有正确阅读它,但您的示例来自
Listing,对吗?我的示例将从Listings的集合中调用,那么它将如何工作?类似IEnumerable listings = "all listings";`listings.Categories.Where(x => listIds.Any(y => x.Id = y)); -
dbContext.Listing.Where(x => listIds.Any(y => x.Categories.Id = y))我的坏
标签: c# sql-server entity-framework linq entity-framework-6