C# 如何使用代码迁移配置禁用延迟加载、实体框架4.1

C# 如何使用代码迁移配置禁用延迟加载、实体框架4.1,c#,entity-framework-4.1,C#,Entity Framework 4.1,这是我用来配置数据库的代码: internal sealed class Configuration : DbMigrationsConfiguration<DataStore> { public Configuration() { AutomaticMigrationsEnabled = true; SetSqlGenerator("System.Data.SqlServerCe.4.0", new SqlCeModelColumn

这是我用来配置数据库的代码:

 internal sealed class Configuration : DbMigrationsConfiguration<DataStore>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        SetSqlGenerator("System.Data.SqlServerCe.4.0", new SqlCeModelColumnBugWorkaroundProvider());

    }

    protected override void OnSeed(DbContext context)
    {
       context.Configuration.LazyLoadingEnabled = false;
       new SeedData(context as DataStore);
    }

    public static void DoDatabaseInitialisation()
    {
        var setting = ConfigurationManager.AppSettings["RequiresDbUpdate"];
        var requiresDbUpdate = bool.Parse(string.IsNullOrEmpty(setting) ? "false" : setting);

        if (! requiresDbUpdate) return;

        //otherwise create/update the database 
        var dbMigrator = new DbMigrator(new Configuration());
        dbMigrator.Update();

        ResetDbUpdateRequired("/");
    }

    private static void ResetDbUpdateRequired(string appPath)
    {
        var hostName = WebHelper.GetHost(false);

        if (!hostName.Contains("localhost"))
            WebHelper.UpdateWebConfigAppSetting("RequiresDbUpdate", "false", appPath);
    }
内部密封类配置:dbmigtorinsconfiguration
{
公共配置()
{
AutomaticMiggerationsEnabled=真;
SetSqlGenerator(“System.Data.SqlServerCe.4.0”,新的SqlCeModelColumnBugWorkaroundProvider());
}
种子上受保护的覆盖无效(DbContext上下文)
{
context.Configuration.LazyLoadingEnabled=false;
新的种子数据(作为数据存储的上下文);
}
公共静态无效DoDatabaseInitialization()
{
var setting=ConfigurationManager.AppSettings[“RequiresDbUpdate”];
var requiresDbUpdate=bool.Parse(string.IsNullOrEmpty(设置)-“false”:设置);
如果(!requiresDbUpdate)返回;
//否则,创建/更新数据库
var dbmigator=new dbmigator(new Configuration());
dbMigrator.Update();
ResetDbUpdateRequired(“/”);
}
需要私有静态void ResetDbUpdateRequired(字符串appPath)
{
var hostName=WebHelper.GetHost(false);
如果(!hostName.Contains(“localhost”))
UpdateWebConfigAppSetting(“RequiresDbUpdate”、“false”、appPath);
}
如果有人知道怎么做,请告诉我。我也在模型类上尝试了非虚拟属性,但这似乎没有任何区别。

我一直使用

context.Configuration.LazyLoadingEnabled = false;
在使用DbContext方法之前调用它,等效设置如下:

(context as IObjectContextAdapter).ObjectContext.ContextOptions.LazyLoadingEnabled = false;

Max的解决方案离这一点不远。实际上促使我去另一个地方或解决方案寻找。看起来你可能首先使用了EF代码,是吗?所以,在你的上下文初始化中,有“OnModelCreated”的覆盖

在这个方法中,我只需调用并设置属性,就可以解决所有问题

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
     base.Configuration.LazyLoadingEnabled = false;
}

我的模型现在更受欢迎了。延迟加载很好…但不是在你不想要它的时候。而且当你开始使用循环引用时,这简直是荒谬的。

是的,我已经尝试过这种方法,它在没有代码优先迁移的情况下正常工作。所以我认为这与此有关,为什么它不起作用。。。