How Do I Disable Lazy Loading, Entity Framework 4.1 using Code Migrations Configuration

拜拜、爱过 提交于 2019-12-07 06:40:25

问题


This is the code im using to configure the database:

 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);
    }

If anybody knows how to do this, please let me know. I have also tried non-virtual properties on the model classes but this seems to make no difference at all.


回答1:


I've always used

context.Configuration.LazyLoadingEnabled = false;

calling it before using the DbContext methods, an equivalent setting is this:

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



回答2:


Max's solution isn't far from the point. Actually spurred me to look in a different location or the solution. Seems like you may be using EF Code First, yeah? So, in the Initialization of your context, there is the override of 'OnModelCreated'.

In this method, I simply called up and set the property and all was resolved.

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

My model is now much more palatable. Lazy loading is great...but not when you don't want it. And when you start having circular references, it's just ridiculous.



来源:https://stackoverflow.com/questions/9033966/how-do-i-disable-lazy-loading-entity-framework-4-1-using-code-migrations-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!