繁体   English   中英

EF包括孩子对父母兄弟姐妹的参考

[英]EF is including Child's reference back to Parent's siblings

我正在查询交货,并包括其中一个属性(“物料类型”),它返回的一切都很好,但我的“物料类型”具有“交货”列表。 因此,其返回的传递同级。

这是我的课程:

public class Delivery
{
    public int DeliveryId { get; set; }
    public DateTime DeliveryDate { get; set; }
    ...
    public int MaterialTypeId { get; set; }
    public virtual MaterialType MaterialType { get; set; }
}

public class MaterialType
{
    public int MaterialTypeId { get; set; }
    public string Name { get; set; }
    ...
    public virtual ICollection<Delivery> Deliveries { get; set; }
}

这是我按日期范围查询的送货

var deliveries = DataStore.Filter<Delivery>(i =>
                 i.DeliveryDate >= startDate && i.DeliveryDate < endDate
                 ,new string[] { "MaterialType" }) // Includes
                 .OrderByDescending(i => i.DeliveryDate).ToList();

public virtual IQueryable<T> Filter<T>(Expression<Func<T, bool>> predicate, string[] includes = null) where T : class
{
    IQueryable<T> set = dbContext.Set<T>();
    if (includes != null && includes.Count() > 0)
    {
        foreach (var include in includes)
        {
            set = set.Include(include);
        }
    }
    return set.Where<T>(predicate).AsQueryable<T>();
}

这是我从查询中获得的结果,Delivery.MaterialType.Delivery正在使用原始Delivery的同级填充。

[{
    "DeliveryId": 1,
    "DeliveryDate": "2017-05-22",
    "MaterialTypeId": 2,
    "MaterialType": {
        "MaterialTypeId": 2,
        "Name": "Bulk",
        "Deliveries": [{
            "DeliveryId": 2,
            "DeliveryDate": "2017-05-22",
            "MaterialTypeId": 2,
        },
        {
            "DeliveryId": 3,
            "DeliveryDate": "2017-05-22",
            "MaterialTypeId": 2,
        }]
    }
}]

延迟加载设置为禁用。

dbContext.Configuration.LazyLoadingEnabled = false;

有什么方法可以防止MaterialTypes填充交货?

我不确定这里的延迟加载是否有错,相反,这可能与自动建立关系有关。

假设您有物料类型为A的交货A,物料类型为A的交货B。 如果您对交货发出查询并包括物料类型,则物料类型A中的交货清单将同时包含交货A和交货B,因为无论如何查询都会将它们装载到上下文中。

禁用延迟加载只会告诉EF访问属性时不要加载任何实体,但是它并没有说明如何修复上下文中已经存在的实体之间的关系。

如果使用同一个DbContext对象发出多个查询,则可能会发生相同的情况:运行查询并实现结果后,这些对象将位于上下文中。 因此,如果您在相同的上下文中发出另一个查询,其中结果对象之一引用了以前加载的实体,则导航属性将根据上下文中的对象自动填充。

您要序列化的对象已启用“延迟加载”,因此它正在填充所有属性。 在查询之前,请禁用像这样的延迟加载:

DataStore.Configuration.LazyLoadingEnabled = false;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM