实体框架总是包含上下文中的数据,即使我不要求它 [英] Entity Framework always includes data that is in context even if I don't ask for it

查看:92
本文介绍了实体框架总是包含上下文中的数据,即使我不要求它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVC.NET Web api,EF与DB首先,我的懒惰加载在我的上下文关闭。 EF返回方式太多的数据,即使关闭了LazyLoading。



例如,我拥有一个角色的用户。当我查询用户和包含角色时,Role.Users属性将自动填充数据,因为用户已被加载到上下文中。



为什么我不能获得EF给我JUST我要求什么?或者我在这里缺少一些东西?

  public partial class User 
{
public int UserID {get ;组; }
public string标题{get;组; }
public string Email {get;组; }
public int RoleID {get;组; }

....

public virtual角色角色{get;组;
}

public partial class Role
{
public int RoleID {get;组; }
public string RoleName {get;组; }

....

public virtual ICollection< User>用户{get;组; }
}




return db.Users.Include(u => u.Role);
// ^^ user.Role.Users填充1000个用户

TL; DR - 我希望EF永远不会将数据加载到导航属性/集合中,除非我直接(。当序列化到JSON时,我想要明确要求的。似乎即使是延迟加载,已经在上下文中的导航属性(通常是循环引用)将被加载并返回。

解决方案

您所看到的行为称为 关系修正 ,您无法禁用



如果您正在加载用户的角色来序列化它们并将其发送到某个地方,我猜你不想跟踪他们拥有的上下文中实体的更改因此,没有必要将它们附加到上下文中,您可以使用:

  return db.Users。 Include(u => u.Role).AsNoTracking(); 

或者将投影用于专门用于序列化的对象,如@STLRick所建议的。


I am using MVC.NET web api, EF with DB first, and I have lazy loading turned off on my context. EF is returning way too much data, even with LazyLoading turned off.

For example, I have Users with one Role. When I query for Users and Include Role, the Role.Users property is automatically filled with data since Users have been loaded into the context.

Why can't I get EF to give me JUST what I request? Or am I missing something big here?

public partial class User
{
    public int UserID { get; set; }
    public string Title { get; set; }
    public string Email { get; set; }
    public int RoleID { get; set; }

    ....

    public virtual Role Role { get; set; }
} 

public partial class Role
{
    public int RoleID { get; set; }
    public string RoleName { get; set; }

    ....

    public virtual ICollection<User> Users { get; set; }
} 




return db.Users.Include(u => u.Role);
// ^^ user.Role.Users is filled with 1000s of users

TL;DR - I want EF to never load data into navigation properties/collections unless I .Include() it directly. When serializing to JSON I want just what I ask for explicitly. It seems that even with lazy loading off, navigation properties that are already in the context (ie usually "circular references") will be loaded and returned.

解决方案

The behaviour your are seeing is called Relationship Fixup and you cannot disable it.

If you are loading users with roles to serialize them and sent them to somewhere I guess that you don't want to track changes of entities in the context they have been loaded in. So, there is no need to attach them to the context and you can use:

return db.Users.Include(u => u.Role).AsNoTracking();

Or use a projection into an object specialized for serialization, as suggested by @STLRick.

这篇关于实体框架总是包含上下文中的数据,即使我不要求它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆