Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ基于与子元素的匹配返回元素_C#_Entity Framework_Linq - Fatal编程技术网

C# LINQ基于与子元素的匹配返回元素

C# LINQ基于与子元素的匹配返回元素,c#,entity-framework,linq,C#,Entity Framework,Linq,我希望这个标题有点道理 我试图生成一个LINQ查询,当子对象的子对象的所有元素与父元素上的属性不匹配时,该查询将返回这些元素 希望我没有失去你的描述。我认为一个具体的例子可能有助于解释我正在尝试做什么 我有三个类和一个枚举: public class Studio { public int StudioId { get; set; } public string StudioName { get; set; } public Style Style { get; set;

我希望这个标题有点道理

我试图生成一个LINQ查询,当子对象的子对象的所有元素与父元素上的属性不匹配时,该查询将返回这些元素

希望我没有失去你的描述。我认为一个具体的例子可能有助于解释我正在尝试做什么

我有三个类和一个枚举:

public class Studio
{
    public int StudioId { get; set; }
    public string StudioName { get; set; }
    public Style Style { get; set; }

    public virtual ICollection<Designer> Designers { get; set; }
}

public class Designer
{
    public int DesignerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int StudioId { get; set; }

    public virtual Studio Studio { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public decimal Price { get; set; }
    public int DesignerId { get; set; }
    public Style ProductStyle { get; set; }

    public virtual Designer Designer { get; set; }
}

public enum Style { Classic, Preppy, Modern, Punk, Goth }

您可以通过设置的导航属性访问属于
工作室的产品。然后很容易检查
Product.ProductStyle
Studio.Style
之间的不匹配:

from s in context.Studios
where s.StudioId == studio.StudioId
from d in s.Designers
from p in d.Products
where p.ProductStyle != s.Style
select p
顺便说一下,您必须按id查找
Studio
。EF不允许您在LINQ查询中使用
Studio
变量。

尝试:

 var products=studios.SelectMany(s => s.Designers
            .SelectMany(d => d.Products.Where(p => p.ProductStyle != s.Style)))
                .ToList();

考虑对多个
from
语句使用SQL风格的LINQ语法,以使用“嵌套”列表创建查询

(相当于
.SelectMany()
扩展方法)

扩展方法也是有效的;但对于嵌套列表,我个人认为SQL风格的语法在表达意图方面更加清晰(可读性更强)。当存在多个嵌套级别时,
。SelectMany
可能会稍微不太清晰

 var products=studios.SelectMany(s => s.Designers
            .SelectMany(d => d.Products.Where(p => p.ProductStyle != s.Style)))
                .ToList();
var products =
        from s in StudioContext.Studios.Where(s => s == studio)
        from d in s.Designers
        from p in d.Products
        where p.ProductStyle != s.Style
        select p;