Running Entity Framework (Core) commands in Rider

Maarten Balliauw

A while back, we received a very interesting question: how can we run Entity Framework commands like adding migrations or updating the database, in Rider?

In Visual Studio, Entity Framework commands like Add-Migration and Update-Database are typically run in the Package Manager Console. This works great, but unfortunately, it isn’t very portable. These commands are PowerShell-based, and the Package Manager Console ties to several Visual Studio-specific objects making it impossible to host it elsewhere.

No need to worry, though! With Entity Framework Core, Microsoft provides command line tools that work cross-platform, which in this case means in any IDE on any supported operating system. Let’s see how to get started!

Adding package references

The first thing to do would be adding package references. There are a few packages we’ll be needing, the first four are typically already installed when working with Entity Framework Core:

Edit for .NET Core 3 – the package names have been changed for .NET Core 3, and are now:

        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0">
            <PrivateAssets>all</PrivateAssets>
            <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
        </PackageReference>

We can add package references using the NuGet tool window or by hand-editing the .csproj file. Since there are a couple of references to add, let’s select the project in the solution explorer, Jump to Source (F4) and manually add the required package references.

Edit .csproj file using Jump to Source

(Here’s a gist if you want to copy-paste the references)

Note that Microsoft.EntityFrameworkCore.Tools.DotNet is added as a “.NET CLI tool” reference, meaning it will extend the command line dotnet command.

Once added, Rider will run a package restore and download all required packages onto our system. We can now execute Entity Framework Core commands!

Entity Framework Core commands

Commands can be run from the built-in terminal (double-shift and type “terminal”). By default, the terminal opens in our solution folder. Since the Entity Framework Core command line tools are project specific, we’ll have to cd into the project folder. To test if we’re in the correct folder, run dotnet ef. If we see an Entity Framework unicorn in ASCII art, we’re ready to go.

Usign Rider terminal to run Entity Framework command line tools

If you see an error “No executable found matching command dotnet-ef”, you may have to run a manual dotnet restore from the command line first, or explicitly run dotnet tool install --global dotnet-ef to install the command line tools.

Let’s start by scaffolding a new database context, using the dotnet ef dbcontext scaffold command. It takes a connection string and the driver package to use, and we’ll also give it a name:

dotnet ef dbcontext scaffold "Server=(localdb)\MSSQLLocalDB;Integrated Security=true;" Microsoft.EntityFrameworkCore.SqlServer -c AcmeDataContext

This adds a file named AcmeDataContext.cs, which implements the data context we’ll be using while developing our application. Let’s add a Person class, as well as a DbSet<Person> inside of our AcmeDataContext:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public partial class AcmeDataContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
        optionsBuilder.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Integrated Security=true;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }

    public DbSet<Person> People { get; set; }
}

By adding the DbSet<Person>, we’re telling Entity Framework Core to include and track a set of Person objects. In other words: we’re telling it we want to store some data in a table.

We can now create an initial database migration. In Entity Framework, migrations can be executed one by one to bring a database schema to the latest version (or rollback to an older version). Let’s call it “AddPerson”:

dotnet ef migrations add AddPerson

This generates a couple of things. It’s our first migration, so a folder named “Migrations” is added to our project. Under this folder, several files are created, some of them prefixed with a number. This number is a timestamp used for ordering the migrations that will be run, making sure our database schema doesn’t get corrupted by applying migrations. These are the files on my machine:

  • 20170804084416_AddPerson.cs – the code that, in this case, creates the People table in our database and adds a primary key. We can hand-edit this one, as long as we have not applied the migration to our database yet.
  • 20170804084416_AddPerson.Designer.cs – designer information. Don’t touch it as it helps Entity Framework with some details about the migration we created.
  • AcmeDataContextModelSnapshot.cs – A snapshot of the current database model, used by Entity Framework Core to determine the database structure.

One more step: applying the database migration and bringing the database up-to-date with our model.

dotnet ef database update AddPerson

There we go: we can now use our Entity Framework Core data context in code and query, add, update and delete Person objects in there.

The dotnet ef command has some more options. Check the documentation for more info.

Connecting to our database with the Rider database tools

Working with Entity Framework is one thing, while developing we may also want to inspect the database schema or run arbitrary SQL queries against the database itself. We can do this using Rider’s database tools, which are based on our IDE for databases: DataGrip.

The database tools are available from the View | Tool Windows | Database menu (double-shift and type “database”). We can create a new database connection, and select the type of database we want to work with. In the first part of this post, we used SQL Server LocalDB, so we can add a new datasource that targets SQL Server (jTds). Do make sure to check the steps described on the DataGrip blog!

Create SQL Server LocalDB connection using jTDS

Once the connection is configured, we can see our tables and work with the data stored in there. We can export data, import data, run arbitrary queries, … A great companion to Entity Framework!

Rider database tools in action

Want to give it a try? Download Rider now! We’re eager to hear your feedback!

Comments below can no longer be edited.

33 Responses to Running Entity Framework (Core) commands in Rider

  1. Dew Drop – May 26, 2016 (#2260) | Morning Dew says:

    May 26, 2016

    […] Open sourcing ReSharper’s external annotations (Matt Ellis) […]

  2. Szumma #041 – 2016 21. hét | d/fuel says:

    May 30, 2016

    […] Open sourcing ReSharper’s external annotations […]

  3. Harry says:

    September 8, 2016

    How can I get the new JetBrains.ExternalAnnotations 10.2.0 into R# 9.2? It is not listed in the Extension Manager. You wrote “ReSharper 9 shipped them as a bundled plugin, and will prompt you to update them”. This doesn’t happen, I’m only prompted to update to R# 2016.2 which is currently no option for me because of company policies.

  4. Paul Reid says:

    August 9, 2017

    Does this mean there’s no chance we’ll ever be able to use Rider for EF6 projects? If the package manager console is impossible to host elsewhere, then we’ll always need a VS license 🙁

    • Maarten Balliauw says:

      August 9, 2017

      It’s something we are looking into but can’t commit to, yet. Best to follow the tracking issue https://youtrack.jetbrains.com/issue/RIDER-435

      • Paul Reid says:

        August 10, 2017

        Ah, so there is hope! If you guys think there’s a way to support EF6 in Rider, it might be worth changing the wording of the blog – it suggests there’s no hope! Very glad to hear there is! Thanks for all your efforts! 🙂

  5. Dew Drop - August 10, 2017 (#2539) - Morning Dew says:

    August 10, 2017

    […] Running Entity Framework (Core) commands in Rider (Maarten Balliauw) […]

  6. Chris says:

    September 8, 2017

    A line in the gist file makes the ‘dotnet ef’ command return the error ‘Version for package `Microsoft.VisualStudio.Web.CodeGeneration.Tools` could not be resolved.
    ‘ on OSX.
    This line causes it:
    DotNetCliToolReference Include=”Microsoft.VisualStudio.Web.CodeGeneration.Tools” Version=”1.0.1″
    If you remove it or change the version to 1.0.0 it works though.

  7. Dawid says:

    October 3, 2017

    Does anyone have any idea how to resolve this issue ?

    “Package ‘Microsoft.VisualStudio.Web.CodeGeneration.Tools 1.0.2’ has a package type ‘DotnetCliTool’ that is not supported by project ”

    I tried most of the stuff posted on the net, but nothing works, adding it via nuget nor editing csproj. This acutally causes the dotnet ef error.

  8. Maarten Balliauw says:

    October 3, 2017

    This should be resolved by adding:

    <DotNetCliToolReference Include=”Microsoft.VisualStudio.Web.CodeGeneration.Tools” Version=”1.0.2″ />

    • Dawid says:

      October 3, 2017

      I think You missed the paste 😀

      • Maarten Balliauw says:

        October 3, 2017

        HTML entities 😉

        • Dawid says:

          October 3, 2017

          Hmm there is no error anywhere but still after doing dotnet restore, the dotnet ef throws

          ‘No executable found matching command “dotnet-ef”‘ .

          Why its always has to be so complicated 🙂

          • Maarten Balliauw says:

            October 3, 2017

            Probably because the terminal opens in the solution folder. Can you try to “cd” into the project folder and then run dotnet ef?

            • Dawid says:

              October 3, 2017

              Ye i noticed that, but i cant edit comments here :). Thanks for the help 🙂

  9. Dmitrij says:

    August 1, 2018

    But how to add-migration on EntityFramework 6.0?
    I tried using inline tool, but tool did not apear with connection to MsSqlLocal.Dmitrij

  10. Dmitrij says:

    August 1, 2018

    But how to add-migration on EntityFramework 6.0?
    I tried using inline tool, but tool did not apear with connection to MsSqlLocal.

  11. Christian Vasquez says:

    October 6, 2018

    Hey guys,

    Has anyone tried using this in macOS? Whenever I run the command:

    dotnet ef dbcontext scaffold “Server=(localdb)\MSSQLLocalDB;Integrated Security=true;” Microsoft.EntityFrameworkCore.SqlServer -c AcmeDataContext

    I get the following exception:

    “System.PlatformNotSupportedException: LocalDB is not supported on this platform.”

    I’ve read about SQL LocalDB not being supported for macOS, then what would be the right command to execute?

    In case it helps, I’m already using Docker to use SQL Server for Linux and I’m able to connect to it from Rider or DataGrip successfully.

    • Maarten Balliauw says:

      October 8, 2018

      Looks like you may want to provide the connection string to your Dockerized SQL server instead of the LocalDB connection string?

  12. Andrew Morris says:

    February 10, 2019

    Is it possible to create a migration against a .net standard csproj? I have a .net core proj that references a .net standard proj where the db content and entities live. When trying to create a migration using the following, I get the following error:

    dotnet ef migrations add DbInit -p AndrewMorris.Hub.csproj -s AndrewMorrisPortal.csproj

    Error:

    MSBUILD : error MSB1009: Project file does not exist.
    Switch: AndrewMorris.Hub.csproj
    Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. If you're using custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.

    • Maarten Balliauw says:

      February 11, 2019

      From the error, it looks like the project is not being found. This could be because dotnet ef is called from the wrong directory. If you have a solution and those 2 projects, the command will have to be run from the directory that holds your solution file.

  13. ifnk says:

    September 22, 2019

    No project was found. Change the current working directory or use the –project option.

    how can i solve it ?

    • Maarten Balliauw says:

      September 25, 2019

      Double-check you are in a project folder and not in the solution folder.

  14. DaveW says:

    October 15, 2019

    Is the nuget package reference list above still correct for EF Core 3? I keep getting errors when trying to add migrations or update database from a multi project solution. Have tried running the correct commands from all of the directories (Solution directory and all 3 project directories) and still get error. I have no db code in my startup (which is common problem as per Microsoft update core 2 to core 3 docs – mine is a fresh core 3 solution).
    Thanks

    • Maarten Balliauw says:

      October 15, 2019

      Just updated the post wit the correct packages. For tooling, you’ll want Microsoft.EntityFrameworkCore.Tools

  15. Virgil says:

    October 20, 2019

    i couldnt use `dotnet ef` and i kept getting the same error after using dotnet restore.
    so i looked it up and since i was using dotnet core 3 i got here :
    https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet
    seemingly the problem is solved running the following as it solved it for me:
    dotnet tool install –global dotnet-ef

  16. Shea Martin says:

    November 26, 2019

    Sadly using EF Code First in Rider has not improved from the time of writing this article.

    Every time I perform an entity framework action in the I have to fill in all the information before running a command: project, configuration type, config project, config file, config source, log level, etc. It is so painful and error-prone that most people I know just keep Visual Studio open just so they can run the EF commands like add-migration and update-database on the PM console of VS. Is there anyway we can set the default values for a project? This feature was clearly developed by someone who does not do EF code first development… i.e., not dog-fooding the product.

  17. Oliver says:

    April 7, 2020

    For anyone else that ends up and is banging their head against a wall

    dotnet tool install –global dotnet-ef

  18. Andrew says:

    April 16, 2020

    Thanks Oliver,

    Just wanted to follow up, as your post was really helpful, that there is an additional dash in front of the global.

    dotnet tool install --global dotnet-ef

    • Maarten Balliauw says:

      April 17, 2020

      Thanks Andrew (added code tags to your comment so it renders nicely).
      I’ll update the blog post with this one as well.

  19. Chester Husk says:

    April 19, 2020

    I’d like to suggest that you all show how to set up the tools using a local tool manifest instead of the global install of `dotnet-ef`. Global installs are not portable, and the local manifest is the officially-supported way forward IMO. Related issue on the EF help itself is at https://github.com/dotnet/EntityFramework.Docs/issues/2144

Subscribe

Subscribe to .NET Tools updates