如何与孩子一起获取家长数据对孩子有适用条件

时间:2018-10-03 19:15:32

标签: c# entity-framework linq

我不知道我的问题标题是什么。

我有两个班级

public class Product
{
    public int Id { get; set; }

    public string Name { get; set; }  

    public virtual ICollection<Spec> Specs { get; set; }
}

public class Spec
{
    public int Id { get; set; }

    public string Name { get; set; }

    public bool IsActive { get; set; }

    public virtual Product Product { get; set; }
}

现在,如果在LINQ中,规范IsActive为true,则需要获得具有规范的产品。 我已经尝试过但没有得到任何结果。

var products = db.Products.Where(x => x.Specs.All(a => a.IsActive)).ToList();

但是我的预期结果没有得到。

2 个答案:

答案 0 :(得分:0)

您从数据库中获取产品。延迟加载产品不会加载规范,请尝试将其包括在内:

var products = db.Products.Include("Specs").Where(x=>x.Specs.All(a=>a.IsActive)).ToList();

答案 1 :(得分:0)

class Program
{
    static void Main(string[] args)
    {
        var p = new List<Product>();

        p.Add(new Product() { Id = 1, Specs = new List<Spec>() { new Spec() { Id = 90, IsActive = true }, new Spec() { Id = 91, IsActive = false } } });
        p.Add(new Product() { Id = 2, Specs = new List<Spec>() { new Spec() { Id = 92, IsActive = false }, new Spec() { Id = 93, IsActive = false } } });
        p.Add(new Product() { Id = 3, Specs = new List<Spec>() { new Spec() { Id = 94, IsActive = true}, new Spec() { Id = 95, IsActive = true} } });
        p.Add(new Product() { Id = 4, Specs = new List<Spec>() { new Spec() { Id = 96, IsActive = true }, new Spec() { Id = 97, IsActive = true } } });


        //Brings Products with ALL Spec.IsActive True
        var products = p.Where(x => x.Specs.All(a => a.IsActive)).ToList();
        Console.WriteLine("ALL ->" + string.Join(",", products.Select(pro => pro.Id.ToString()).ToArray()));
        //result is 3,4

        //Brings Products with ANY Spec.IsActive True
        var products2 = p.Where(x => x.Specs.Any(a => a.IsActive)).ToList();
        Console.WriteLine("ANY ->" + string.Join(",", products2.Select(pro => pro.Id.ToString()).ToArray()));
        //result is 1,3,4

        Console.ReadLine();
    }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }


    public virtual ICollection<Spec> Specs { get; set; }
}

public class Spec
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }


    public virtual Product Product { get; set; }
}