c# - LINQ 根据与子元素的匹配返回元素

标签 c# entity-framework linq

我希望标题有意义。

我正在尝试生成一个 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 }

每个工作室都有其整体Style ,以及每个Product有自己的风格。在某些情况下,Product可能会显示在 Studio具有不匹配的风格理念。

我可以生成一个 LINQ查询返回 IEnumerable<Product>包含所有ProductsStudio这是不匹配的吗?

我创建了一个有效的三重嵌套循环,但我希望得到一些帮助,将其转换为 LINQ 语句(使用点表示法):

public IEnumerable<Product> GetProductsWithOutsideStyles(Studio studio)
{
    List<Product> products = new List<Product>();

    foreach (Studio s in StudioContext.Studios.Where(s => s == studio))
    {
        foreach(Designer d in s.Designers)
        {
            foreach(Product p in d.Products)
            {
                if (p.ProductStyle != s.Style)
                    products.Add(p);
            }
        }
    }

    return products;
}

最佳答案

您可以通过您设置的导航属性访问属于 Studio 的产品。然后很容易检查 Product.ProductStyleStudio.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 变量。

关于c# - LINQ 根据与子元素的匹配返回元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41515293/

相关文章:

c# - 有什么方法可以模拟直接在方法中创建新连接的 Entity Framework 调用

c# - 如何检查 linq 查询中的空值?

C# LINQ 状态的DeleteOnSubmit()

c# - 在 C# 中更改波特率而不关闭连接

c# - 使用由 MEF 加载的模型类型的 ASP.Net MVC View 导致 View 构建器中的 JIT 编译错误

c# 使用 XPathDocument 解析 html

c# - 目标程序集不包含任何服务类型。您可能需要调整此程序集的代码访问安全策略

entity-framework - 如何在 C# 中序列化 typeof 模型

c# - 将单个对象转换为多个对象 c#

c# - 为通用 C# 集合中的每个值调用一个函数