Bas*_*maa 20 asp.net-mvc linq-to-entities entity-framework entity-framework-4 entity-framework-5
我有这两个类:
public class BusinessesTBL
{
public string ID { get; set; }
public string FirstName { get; set; }
public string lastName { get; set; }
public ICollection<OffersTBL> OffersTBLs { get; set; }
}
public class OffersTBL
{
public int ID { get; set; }
public string Name { get; set; }
public int CatId { get; set; }
public string BusinessesTBLID { get; set; }
public virtual BusinessesTBL BusinessesTBLs { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当我尝试根据CatId字段提供所有优惠时,我还需要返回BusinessesTBLs,但该方法还会根据每个BusinessesTBL obj返回优惠,我的代码是:
public IQueryable<OffersTBL> GetOffersTBLsCat(int id)
{
db.OffersTBLs.Include(s => s.BusinessesTBLs);
}
Run Code Online (Sandbox Code Playgroud)
你可以看到错误的结果:http: //priooffer.azurewebsites.net/api/OffersApi/GetOffersTBLsCat/4
正如您所看到的,它返回每个Business对象下的所有商品,而每个商品对象下的商品对象,我只希望在Business obj下返回商品对象的商品.
有人可以帮忙吗?
Fab*_*Luz 10
您已在OffersTBLs上停用延迟加载,使其成为非虚拟加载.如果激活延迟加载怎么办?像这样:
public class BusinessesTBL
{
public string ID { get; set; }
public string FirstName { get; set; }
public string lastName { get; set; }
//put a virtual here
public virtual ICollection<OffersTBL> OffersTBLs { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后,确保在序列化时不要调用/包含OffersTBLs.如果OffersTBLs仍在返回,那是因为您正在代码中的某处获取它们.如果发生这种情况,请编辑您的问题并粘贴所有代码,包括序列化逻辑.
发生这种情况是因为实体框架执行关系修正,这是当属于那里的对象存在于上下文中时自动填充导航属性的过程.因此,使用循环引用,即使禁用延迟加载,也可以无限地向下钻取导航属性.Json序列化器正是这样做的(但显然它已被指示处理循环引用,因此它不会被困在无限循环中).
诀窍是防止关系修复不断下降.关系修复依赖于上下文ChangeTracker,它缓存对象以跟踪其更改和关联.但是如果没有什么可追踪的话,就没有什么可以解决的了.您可以通过以下方式停止跟踪AsNoTracking():
db.OffersTBLs.Include(s => s.BusinessesTBLs)
.AsNoTracking()
Run Code Online (Sandbox Code Playgroud)
除此之外,您还要在上下文中禁用延迟加载(通过设置contextConfiguration.LazyLoadingEnabled = false),您将看到仅OffersTBL.BusinessesTBLs在Json字符串中填充并且BusinessesTBL.OffersTBLs是空数组.
奖励是AsNoTracking()提高性能,因为更改跟踪器不忙于跟踪EF实现的所有对象.实际上,您应该始终在断开连接的设置中使用它.