Entity Framework Core — From zero to something

Oli Blade
Oli & Tom
Published in
3 min readSep 30, 2020

I… have never used Entity Framework before. But when someone pitched me the idea of removing all my CRUD stored procedures I jumped right in with my new ASP.NET Core 3.1 project.

Getting started

To begin with, I created a SQL Server Database Project in Visual Studio with a couple of tables that reference each other so we have something to play with.

CREATE TABLE [dbo].[Campaigns]
(
[CampaignId] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
[Name] NVARCHAR(100),
[Enabled] BIT,
[UserId] NVARCHAR(450) NOT NULL
)
CREATE TABLE [dbo].[CampaignFilters]
(
[CampaignFilterId] INT NOT NULL PRIMARY KEY IDENTITY,
[CampaignId] UNIQUEIDENTIFIER NOT NULL,
[FilterTypeId] INT NOT NULL

CONSTRAINT [FK_CampaignFilters_Campaigns] FOREIGN KEY ([CampaignId]) REFERENCES [Campaigns]([CampaignId])
)

Next, I used the Schema Compare feature in Visual Studio to add my tables to my Database.

Database in SSMS

With my new tables safely in SQL Server it was time to move on to some Entity Framework things.

Generating the models

Easy as 1…2…3

1. Run the command in Visual Studio Package Manager Console to scaffold the models and Model Context (the thing that tells the models what they are)

Scaffold-DbContext ”Server=localhost;Database=EntityFrameworkDB;User Id=DBUser;Password=Password;” -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/Database -force

2. Realise the scaffolded models have weird pluralisation

Why is it plural? Maybe it’s just me :(

3. Install the following Nuget package and try again

Successful scaffolding

Trying it out

I slapped together a couple of CRUD-y read and writes using the models and context I had just made using some dependency injection to get hold of the DBContext.

public class CampaignRepository
{
private EntityFrameworkDBContext EntityFrameworkDBContext { get; }
public CampaignRepository(EntityFrameworkDBContext entityFrameworkDBContext)
{
EntityFrameworkDBContext = entityFrameworkDBContext;
}
public IEnumerable<Campaign> GetCampaignsByUser(string userID)
{
return EntityFrameworkDBContext.Campaigns.Where(x => x.UserId == userID);
}
public void SaveCampaign(Campaign campaign)
{
EntityFrameworkDBContext.Campaigns.Add(campaign);
EntityFrameworkDBContext.SaveChanges();
}
}

And sure enough…. it worked.

Other things I learned along the way

  1. You can run the scaffold command from the DotNet CLI.
dotnet ef DbContext Scaffold “Server=localhost;Database=EntityFrameworkDB;User Id=DBUser;Password=Password;” Microsoft.EntityFrameworkCore.SqlServer -o Models/Database — force

2. You can use stored procedures along side Entity Framework, there’s no ish.

3. Update and Add are not the same thing and will cause errors if used interchangeably.

4. Use the “-force” flag to overwrite your changes

5. You can use partial classes to expand on the models

--

--