Entity Framework, Navigation Properties, and the Repository Pattern

Generic Repository vs Non-generic Repository Generic repository is not a pattern. Generic repository is just a wrapper. It can be useful for some special scenarios as a base class for specific repositories but in most cases it is just over used and over hyped nonsense. Navigation properties Repository itself should be used with aggregate root. … Read more

Include with FromSqlRaw and stored procedure in EF Core 3.1

Shortly, you can’t do that (at least for SqlServer). The explanation is contained in EF Core documentation – Raw SQL Queries – Composing with LINQ: Composing with LINQ requires your raw SQL query to be composable since EF Core will treat the supplied SQL as a subquery. SQL queries that can be composed on begin … Read more

How should I set up my integration tests to use a test database with Entity Framework?

Thanks so much to @Justin and @Petro for your answers, which have helped me immensely. The solution I have come up with is a combination of the techniques you suggested. The solution described below provides a new database for each run of the tests, and a separate transaction for each test. I added a connection … Read more

Can’t auto-generate IDENTITY with AddRange in Entity Framework

What was causing the problem? Enumerables! Take a look at the EDIT section in my question for the solution. EDIT: posting the updated code here as answer. The problem was in the way I used enumerables. Bottom line is you should never trust lazy loading when you need consistent results right away. public class Request … Read more

How can I stop EF Core from creating a filtered index on a nullable column

Creating filtered index excluding NULL values is the default EF Core behavior for unique indexes containing nullable columns. You can use HasFilter fluent API to change the filter condition or turn it off by passing null as sql argument: entityBuilder.HasIndex(e => new { e.LevelId, e.Name, e.DeletedAt }) .IsUnique() .HasFilter(null);

Change or rename a column name without losing data with Entity Framework Core 2.0

EF Core creates its migrations by comparing your models to the current database snapshot (a c# class). It then uses this to create a migration file you can review. However, EF Core cannot always know if you replaced this column or created a new column. When you check your migration file, make sure there are … Read more

Map string column in Entity Framework to Enum

Probably a nicer version. OrderStateIdentifier field is used for both JSON serialization and database field, while OrderState is only used in the code for convenience. public string OrderStateIdentifier { get { return OrderState.ToString(); } set { OrderState = value.ToEnum<OrderState>(); } } [NotMapped] [JsonIgnore] public OrderState OrderState { get; set; } public static class EnumHelper { … Read more