Skip to content

Inspect your DbContext model

Erik Ejlskov Jensen edited this page Dec 10, 2020 · 18 revisions

Add DbContext Model Graph

Adds a DGML graph of the DbContext(s) in you project, that allows you to inspect the relationships and properties on your DbContext Model.

View DbContext Model DDL SQL

Allows you to view the SQL CREATE script in order to create the current DbContext Model.

Challenges

Since the tool needs to load the compiled .dll based on your project and instantiate your derived DbContext(s), there can be a number of challenges preventing/blocking this:

  • You must be able to build the project 😄
  • The model inspection tool (an external process launched by Visual Studio) can be blocked by a virus scanner or similar
  • The model inspection tool requires a compatible .NET Core runtime to be installed.
  • Your DbContext must be configured with a specific provider, or you will get this error: No database provider has been configured for this DbContext.
  • Your DbContext must have a parameterless constructor (or make other designtime helpers available)
  • If you cannot view the model graph, follow the advice here to install the viewer.

Working with .NET Standard 2.0 libraries

You cannot use the two features above with .NET Standard 2.0 libraries, as this project type does not produce any executable build output.

The following workarounds are available:

  • Target .NET Core 3.1 also:

<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>

(Notice the added "s"!) - TargetFrameworks

  • Use the AsDgml() extension method described below.

Add AsDgml() extension method

This menu item installs a NuGet package, that adds the AsDgml() extension method to any derived DbContext.

The method will create a DGML graph of your DbContext Model, that you can view in the Visual Studio DGML viewer.

You can add code like this to in a Unit Test or similar to create the diagram:

    using (var myContext = new MyDbContext())
    {
        var path = Path.GetTempFileName() + ".dgml";
        File.WriteAllText(path, myContext.AsDgml(), Encoding.UTF8);
        var startInfo = new ProcessStartInfo(path)
        {
            UseShellExecute = true,
        };
        Process.Start(startInfo);
    }

This code sample demonstrates using AsDgml to generate a dgml of the context when you visit a ASP.NET Core controller.

Clone this wiki locally