I want to use the solution from @Thanh Nguyen from this question: How do I delete multiple rows in Entity Framework (without foreach)
His solution is this method:
public static void DeleteWhere<T>(this DbContext db, Expression<Func<T, bool>> filter) where T : class
{
var query = db.Set<T>().Where(filter);
string selectSql = query.ToString();
string deleteSql = "DELETE [Extent1] " + selectSql.Substring(selectSql.IndexOf("FROM"));
var internalQuery = query.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(field => field.Name == "_internalQuery").Select(field => field.GetValue(query)).First();
var objectQuery = internalQuery.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(field => field.Name == "_objectQuery").Select(field => field.GetValue(internalQuery)).First() as ObjectQuery;
var parameters = objectQuery.Parameters.Select(p => new SqlParameter(p.Name, p.Value)).ToArray();
db.Database.ExecuteSqlCommand(deleteSql, parameters);
}
You can see the first parameter is of type DbContext. In my project, I use EF 6, database first, but my context class extends from ObjectContext, not DbContext. So as a workaround to use the DeleteWhere extension method I was thinking get the db context from my object context, so I tried this:
using (var db = new MyEntities(connectionString))
{
db.TransactionHandler.DbContext.DeleteWhere(myClause);
}
This works:
using (var db = new MyEntities(connectionString))
{
db.MyTable.DeleteObject(myObject);
}
but the DbContext is null.
What am I doing wrong?