LINQ延迟加载或查询不正确

时间:2018-03-22 19:27:16

标签: linq linq-to-sql linq-to-entities

LINQ查询未填充

模型提取如下

public class ServiceBulletin 
{
    [Key]
    public int Id { get; set; }


    public virtual ICollection<ServiceBulletinProducts> ApplicableProducts { get; set; }

}

public class ServiceBulletinProducts
{
    [Key]
    public int Id { get; set; }

    public int ServiceBulletinId { get; set; }

    public virtual Product Product{ get; set; }
}

我现在使用以下代码来填充集合

var x = from m in _dc.ServiceBulletins.Include(p => p.ApplicableProducts)
                                              .Include(m => m.Manufacturer)                    
                where m.DeleteStatus == DeleteStatus.Active                          
                select m;

        var x1 = new List<ServiceBulletin>();

        foreach (var item in x)
        {
            var p = from m1 in _dc.ServiceBulletinsProducts.Include(p2=>p2.Product)                                                   
                         where m1.Product.DeleteStatus == DeleteStatus.Active &&
                         m1.ServiceBulletinId == item.Id
                         select m1;

            var p99 = p.ToList();
           item.ApplicableProducts = p99;
            x1.Add(item);
        };

因此,这是为了建立一个父子关系,我正在尝试使用ApplicableProducts项填充ServiceBulletins集合的查询,该项包含ServiceBulletin的ServiceBulletinProducts的完全填充集合,其中填充了Product的值< / p>

集合已填充,但ServiceBulletinProducts始终设置为null,我似乎无法添加Include,例如.Include(p =&gt; p.ApplicableProducts.Products)来尝试填充产品详细信息 - 这是导致我在集合周围迭代以填充项目。

我是否遗漏了在Include语句的第一个查询中启用填充的内容,或者我是否需要以不同的方式执行查询?

1 个答案:

答案 0 :(得分:0)

想出以下应该做的伎俩。

      var x = from m in _dc.ServiceBulletins.Include(p => p.ApplicableProducts.Select(p2=>p2.Product))
                                                    .Include(m => m.Manufacturer)
                where m.DeleteStatus == DeleteStatus.Active
                select m;