禁用 entity framework 代理创建和从另一个项目延迟加载
Disable entity framework proxy creation and lazy loading from another project
我有多个项目在同一个解决方案中引用数据库项目,而且一切都很好。我最近在集合中添加了一个 mvc web api 项目,并使用相同的业务服务检索数据。
我只想在 Web 实例中禁用延迟加载和代理创建 api。有没有一种方法可以像在 Gblobal asax 中启动应用程序一样执行此全局操作。
XYZContext.Configuration.ProxyCreationEnabled = 假
XYZContext.Configuration.LazyLoadingEnabled = 假;
我建议为 API 创建单独的上下文,并将设置初始化为所需的值
public class XYZContext : DbContext
{
}
public class XYZContextWithoutLazyLoadingAndProxies : XYZContext
{
public XYZContextWithoutLazyLoadingAndProxies()
{
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
}
或者在构造函数
中使用来自web.config
的配置值
public class XYZContext : DbContext
{
public XYZContext()
{
if (ConfigurationManager.AppSettings["LazyLoading"]?.ToString() == "false")
{
Configuration.LazyLoadingEnabled = false;
}
}
}
我有多个项目在同一个解决方案中引用数据库项目,而且一切都很好。我最近在集合中添加了一个 mvc web api 项目,并使用相同的业务服务检索数据。
我只想在 Web 实例中禁用延迟加载和代理创建 api。有没有一种方法可以像在 Gblobal asax 中启动应用程序一样执行此全局操作。
XYZContext.Configuration.ProxyCreationEnabled = 假 XYZContext.Configuration.LazyLoadingEnabled = 假;
我建议为 API 创建单独的上下文,并将设置初始化为所需的值
public class XYZContext : DbContext
{
}
public class XYZContextWithoutLazyLoadingAndProxies : XYZContext
{
public XYZContextWithoutLazyLoadingAndProxies()
{
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
}
或者在构造函数
中使用来自web.config
的配置值
public class XYZContext : DbContext
{
public XYZContext()
{
if (ConfigurationManager.AppSettings["LazyLoading"]?.ToString() == "false")
{
Configuration.LazyLoadingEnabled = false;
}
}
}