本文介绍了实体框架代码第一 - 多对多 - 包含条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体存储目录,有许多关系使用流利的Api。我想通过 id 获得一个商店,所有目录的状态等于已发布。
下面我尝试写下面的查询,但没有得到预期的结果。

I have two Entities Store and Catalog, having many to many relationship using fluent Api. I want to get a Store by id with all the catalogs having status equals to "Published".Below I try to write the following query but not getting the expected results.

var store = context.Stores.Include("Catalogs").Where(s => s.StoreID == id && s.Catalogs.Any(c => c.Status == "Published")).SingleOrDefault();


推荐答案

你要求的是给我具有此ID的商店,但仅当它具有已发布的目录(任何调用)时。

What you're asking for there is "give me the store with this ID, but only if it has a published catalog" (the "Any" call).

只有获得已发布的目录的最简单的方法是项目他们成为匿名类型:

The easiest way to only get published catalogs would be to project them into an anonymous type:

var result = (from s in context.Stores
             where s.StoreID == id
             select new
             {
                 Store = s,
                 Catalogs = s.Catalogs.Where(c => c.Status == "Published")
             }).SingleOrDefault();

...或在流畅的界面中:

... or, in the fluent interface:

var result = context.Stores.Where(st => st.StoreID == id)
                           .Select(s => new
                           {
                               Store = s,
                               Catalogs = s.Catalogs.Where(c => c.Status == "Published"),
                           }).SingleOrDefault();

所以 result.Catalogs result.Store

这篇关于实体框架代码第一 - 多对多 - 包含条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 05:11