Showing posts with label ORM. Show all posts
Showing posts with label ORM. Show all posts
Tuesday, 22 January 2013

Entity framework delete all entities extension method

Unfortunately when deleting items in entity framework the SQL commands are issued as single DELETE statements for each entity. This really becomes a bottleneck when there are a several thousand items. This handy set of extension methods allows convenient and efficient deletion of all entities for a particular type T. The GetTableName<T> used function even takes into account table mappings set up with the ModelBuilder.

Thanks to Rul Jarimba on StackOverflow for the GetTableName&ltT> function.
public static void DeleteAllEntities<T>(this DbContext db)
    where T : class
{
    var adapter = (IObjectContextAdapter)db;
    var objectContext = adapter.ObjectContext;
    var sql = string.Format("DELETE FROM {0}", objectContext.GetTableName<T>());
    var entityConnection = objectContext.ExecuteStoreCommand(sql);
}

public static string GetTableName<T>(this ObjectContext context) 
    where T : class
{
    string sql = context.CreateObjectSet<T>().ToTraceString();
    Regex regex = new Regex("FROM (?<table>.*) AS");
    Match match = regex.Match(sql);

    string table = match.Groups["table"].Value;
    return table;
}
Friday, 27 April 2012

The lazy loading design pattern

The lazy-loading design pattern provides a means to defer the creation of an object by loading it at the point it is needed. This has both benefits and drawbacks.

Benefits

  • Save memory by only loading what is needed when it's needed.
  • Reduce initial load time by deferring execution.

Drawbacks

  • There may be a delay the first time you need the object you're lazy-loading.

Lazy-loading is often a key feature of ORMs, which perform database queries only when the data is required in order to reduce the amount of data retrieved. This can lead to some issues with certain data not being present, you can usually get around this by explicitly specifying what you need. It is important to understand why this can occur when working with an ORM to prevent obscure bugs.