How to avoid Query Plan re-compilation when using IEnumerable.Contains in Entity Framework LINQ queries?

This is a great question. First of all, here are a couple of workarounds that come to mind (they all require changes to the query): First workaround This one maybe a bit obvious and unfortunately not generally applicable: If the selection of items you would need to pass over to Enumerable.Contains already exists in a … Read more

Entity Framework – Generating Classes

1) First you need to generate EDMX model using your database. To do that you should add new item to your project: Select ADO.NET Entity Data Model from the Templates list. On the Choose Model Contents page, select the Generate from Database option and click Next. Choose your database. On the Choose Your Database Objects … Read more

Getting exact error type in from DbValidationException

While you are in debug mode within the catch {…} block open up the “QuickWatch” window (ctrl+alt+q) and paste in there: ((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors This will allow you to drill down into the ValidationErrors tree. It’s the easiest way I’ve found to get instant insight into these errors. For Visual 2012+ users who care only about the … Read more

EF Core 2: How to apply HasQueryFilter for all entities

In case you have base class or interface defining the IsActive property, you could use the approach from Filter all queries (trying to achieve soft delete). Otherwise you could iterate entity types, and for each type having bool IsActive property build dynamically filter expression using Expression class methods: foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { var … Read more

Using Global Query Filters for all entities

For the latest EF Core version (should work for 3.0 also, for earlier versions expression replacement should be handled manually, see ReplacingExpressionVisitor call) you can automate it using some reflection (minimal amount of it), expression trees and IMutableModel.GetEntityTypes in your OnModelCreating method. Something like this should work: // define your filter expression tree Expression<Func<BaseModel, bool>> … Read more