Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 290
woz Avatar asked Oct 09 '22 21:10

woz


2 Answers

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;
like image 148
Massimo Zerbini Avatar answered Oct 12 '22 12:10

Massimo Zerbini


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.

like image 26
beauXjames Avatar answered Oct 12 '22 11:10

beauXjames