tips (en)‎ > ‎

ef

Boostig Entity Framework Loops

public class Product {

        public int ID { get; set; }
        
public string ShortDescription { get; set; }
       public string Description { get; set; }
}

public class OldVariation {

        public int ID { get; set; }
        public int ProductID { get; set; }
        public virtual ProductModel Product { get; set; }
      
}

public class Variation {

        public int ID { get; set; }
        public int ProductID { get; set; }
        public virtual Product Product { get; set; }
       public string ShortDescription { get; set; }
       public string Description { get; set; }
}

var db = new AppContext();
var oldVariationsdb.OldVariations.ToList();
foreach (var item in oldVariations )
{
var variation = new VariationModel
{
ProductID = item.ProductID ,
Description = item.Product.Description, //because of lazy loading, entity framework is querying the database!
ShortDescription = item.Product.ShortDescription , //because of lazy loading, entity framework is querying the database!//because of lazy loading, entity framework is querying the database!

        };
        
        //if validations pass

        db.Variations.Add(variation);
        db.SaveChanges();
}

This scenario takes ages if the number of OldVariations is very very large. Improvements:
  • eager load product
  • save and dispose db context every n loops
  • context.Configuration.AutoDetectChangesEnabled = false

var db = new AppContext();
var oldVariationsdb.OldVariations.Include(o=>o.Product).ToList();
 var counter = 0;
var threshold = 50;
db.Configuration.AutoDetectChangesEnabled = false;
foreach (var item in oldVariations )
{
var variation = new VariationModel
{
ProductID = item.
ProductID ,
Description = item.Product.Description, //because of eager loading, entity framework is NOT querying the database
ShortDescription = item.Product.ShortDescription /because of eager loading, entity framework is NOT querying the database
};
        
        //if validations pass

        db.Variations.Add(variation);

          counter++;
if (counter >= threshold)
{
db.SaveChanges();
db.Dispose();
db = new AppContext();
db.Configuration.AutoDetectChangesEnabled = false;
counter = 0;
} 
}
       db.SaveChanges();

Create Unique Index with Column that Accepts Null Values in Entity Framework Migration
Sql("CREATE UNIQUE NONCLUSTERED INDEX [IX_ColumnWithNulls]  ON [dbo].[Table]([ColumnWithNulls] ASC) WHERE ([ColumnWithNulls] IS NOT NULL");

Sql("CREATE UNIQUE NONCLUSTERED INDEX IX_Number on dbo.Orders(Number,ID) where Number IS NOT NULL");

Resetting Entity Framework Migrations to a clean Slate
By Rick Strahl
Comments