Created
October 9, 2018 22:54
-
-
Save pgrm/6e7316a776fbb270b2dbd62caa5fe017 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using Microsoft.EntityFrameworkCore; | |
using Z.EntityFramework.Plus; | |
namespace BrokenBatchDeleteExample | |
{ | |
class Program | |
{ | |
public static void Main() | |
{ | |
// An index is required for the key only for SQL Compact. | |
CreateBDWithIndex(); | |
GenerateData(); | |
// Delete: DELETE all rows from the database using a LINQ Query without loading entities in the context | |
using (var context = new EntityContext()) | |
{ | |
// DELETE all customers that are inactive | |
context.Customers.Where(x => !x.IsActive).Delete(); | |
} | |
// Delete: DELETE all rows from the database using a LINQ Query without loading entities in the context | |
using (var context = new EntityContext()) | |
{ | |
// DELETE customers by Name | |
context.Customers.Where(x => x.Name =="Customer_B").Delete(); | |
} | |
} | |
public static void GenerateData() | |
{ | |
using (var context = new EntityContext()) | |
{ | |
context.Customers.Add(new Customer() { Name ="Customer_A", IsActive = false }); | |
context.Customers.Add(new Customer() { Name ="Customer_B", IsActive = true }); | |
context.Customers.Add(new Customer() { Name ="Customer_C", IsActive = false }); | |
context.SaveChanges(); | |
} | |
} | |
public static void CreateBDWithIndex() | |
{ | |
using (var context = new EntityContext()) | |
{ | |
context.Database.EnsureCreated(); | |
} | |
} | |
public class EntityContext : DbContext | |
{ | |
public string NameFilter { get; set; } | |
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) | |
{ | |
optionsBuilder.UseSqlite("Data Source=test.db"); | |
} | |
protected override void OnModelCreating(ModelBuilder modelBuilder) | |
{ | |
base.OnModelCreating(modelBuilder); | |
// THE ACTUAL BUG CAN BE TOGGLED ON / OFF HERE | |
// comment this line of code out, to make the application work | |
modelBuilder.Entity<Customer>().HasQueryFilter(c => string.IsNullOrEmpty(NameFilter) || c.Name == NameFilter); | |
} | |
public DbSet<Customer> Customers { get; set; } | |
} | |
public class Customer | |
{ | |
public int CustomerID { get; set; } | |
public string Name { get; set; } | |
public bool IsActive { get; set; } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment