禁用实体框架代理创建 [英] Disabling Entity Framework proxy creation

查看:58
本文介绍了禁用实体框架代理创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,设置 ProxyCreationEnabled = false 将阻止更改跟踪和延迟加载。但是,我不清楚更改跟踪涵盖哪些内容。

From what I've read, setting ProxyCreationEnabled = false will prevent change tracking and lazy loading. However, I'm not clear on what change tracking covers.

如果我禁用它并从数据库中获取一个实体,请对其进行更改并提交,然后保存这些更改。我仍然可以从ChangeTracker获取修改后的条目:

If I disable it and get an entity from the database, make changes to it and commit, then those changes are saved. I'm also still able to get modified entries from the ChangeTracker:

ChangeTracker.Entries<IAuditable>().Where(x => x.State == EntityState.Modified).ToList()

何时可能我已禁用代理创建?我想禁用它,但是我想清楚我要禁用的内容。

Should this be possible when I've disabled proxy creation? I want to disable it, but I want to be clear on what I'm disabling.

推荐答案

更改跟踪和代理创建是两种不同的情况。如果需要禁用更改跟踪,则必须按如下所示进行操作。

Change tracking and Proxy Creation is two different scenarios. If you need to disable the change tracking then you have to do it as shown below.

public class YourContext : DbContext 
{ 
    public YourContext() 
    { 
        this.Configuration.AutoDetectChangesEnabled = false; 
    }  
}  

然后您将无法执行此操作 ChangeTracker.Entries< IAuditable>()。其中​​(x => x.State == EntityState.Modified).ToList()

Then you cannot do this ChangeTracker.Entries<IAuditable>().Where(x => x.State == EntityState.Modified).ToList().

如果需要禁用代理创建,则必须在上下文的构造函数上进行操作,如下所示。

If you need to disable the Proxy Creation then you have to to do it on the constructor of your context as shown below.

public class YourContext : DbContext 
{ 
    public YourContext() 
    { 
        this.Configuration.ProxyCreationEnabled = false; 
    }  

    public DbSet<Blog> Blogs { get; set; } 
    public DbSet<Post> Posts { get; set; } 
}

代理创建机制用于支持关系的延迟加载。 EF不会为没有代理可做的类型创建代理。换句话说,如果您在POCO类上没有 virtual 属性,那么您是否禁用它都没有效果。

Proxy creation mechanism is used to support lazy loading of relationships. EF will not create proxies for types where there is nothing for the proxy to do. In other words if you don't have virtual properties on your POCO classes then there is no effect either you have disabled it or not.

如果要序列化实体,请考虑关闭代理和延迟加载,因为反序列化代理可能很棘手。

If you’re serializing your entities, then consider switching off proxies and lazy loading since deserializing proxies can be tricky.

您可以阅读有关它的更多信息此处: 使用代理的实体框架

You can read more about it here : Entity Framework Working with Proxies

这篇关于禁用实体框架代理创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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