EntityFramework Core Migration (Code First) — Part IV: Misc Configurations and final code for DbContext and Unit Of Work

Chewy2Theo
2 min readMay 29, 2021

--

Whenever you define one to many or many to many relationships, EF core internally needs to handle what to do when the relationship disappears. For example a student was enrolled in many course works but what happens when the student is deleted, what happens to the Foreign Key that the courses use to link to the student? I personally prefer the FK to go null (as it should be nullabe). For that you can configure the DeleteBehavior for relationships as below. And of course if you look up DeleteBehavior you can find many other possible configurations.

foreach (var relationship in modelBuilder.Model.GetEntityTypes()
.SelectMany(e => e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}

Documentation:

For EF lazy loading can be accomplished when I mark the properties as virtual but in EF core you need to configure Lazy Loading in the startup.cs. While you’re at the startup.cs, configure the split query also. What is split query? That’s something new that you need to configure in EF core. I believe the official documentaion already explained very clearly what the splitQuery does:
https://docs.microsoft.com/en-us/ef/core/querying/single-split-queries

If you do not configure the QuerySplittingBehavior you will receive a warning when you query against the database.

services.AddDbContext<WebBaseEntityContext>(options =>
options.UseLazyLoadingProxies()
.UseSqlServer(Configuration.GetConnectionString("Database String"),
o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)),
ServiceLifetime.Transient);

Finally, this is what the configuration looks like for the Unit Of Work and DbContext

Unit Of Work

DbContext

This article is a part of the .Net to .Net Core Migration Series
https://theochiu2010.medium.com/net-to-net-core-migration-2eb31584f95c

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Chewy2Theo
Chewy2Theo

Written by Chewy2Theo

Just another developer who's into lazy tools that can make my life easier, and hopefully yours too.

No responses yet

Write a response