'How to use lambda expression when defining index filter or check constraint in Entity Framework Core?
Let's say I have an entity that looks something like this
public class ApplicationConfiguration
{
public int Id { get; set; }
public ApplicationId { get; set; }
public string Name { get; set; }
public DeploymentStateType State { get; set; }
}
public enum DeploymentStateType
{
Unknown,
InDeployment,
DeploymentComplete
}
In my model builder, I want to define a filtered index on ApplicationId where State == InDeployment.
Seemingly, the fluent API only allows a hardcoded SQL fragment via this syntax:
modelBuilder.Entity<ApplicationConfiguration>()
.HasIndex(ac => ac.ApplicationId)
.HasFilter("State == 1");
Now this is obviously fragile for two reasons:
- No intellisense/refactoring support for the column name ("State") in the filter expression
- Reference to enum "magic number"
The way I'm solving the problem is:
modelBuilder.Entity<ApplicationConfiguration>()
.HasIndex(ac => ac.ApplicationId)
.HasFilter($"{nameof(ApplicationConfiguration.State)} == {(int)DeploymentStateType.InDeployment}");
But this is obviously ugly and unwieldy.
In an ideal world, I would be able to do specify it using a lambda:
modelBuilder.Entity<ApplicationConfiguration>()
.HasIndex(ac => ac.ApplicationId)
.HasFilter(ac => ac.State == DeploymentStateType.InDeployment);
However, HasFilter() does not seem to have an overload that accepts a lambda. (As of writing, I'm using EF Core 6.0.5 which seems to be the latest stable release.)
This should theoretically be possible, because:
Where()knows how to do it- model builder knows it's building a model from SQL Server dialect, so already at this stage know how to generate correct SQL
This problem pertains to HasCheckConstraint() as well, which also only seems to accept a raw SQL string.
Q: Is there a way to have EF generate the SQL fragment for me, having the filter lambda as an input?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
