Entity Framework Core: View the model as text

 
 
  • Gérald Barré

Note: I use the preview version of Entity Framework Core 2.0 (2.0.0-preview2-final). Things may change after the final version is released

In previous posts, I edited the model to rename generated objects or add properties. Instead of generating a migration script to inspect what gets generated, you can use the ToDebugString extension method to view the model's contents.

C#
using Microsoft.EntityFrameworkCore.Metadata.Internal;

class Program
{
    static void Main()
    {
        using (var context = new BloggingContext())
        {
            Console.WriteLine(context.Model.ToDebugString());
        }
    }
}

This prints the model's contents. You'll find useful data such as properties, keys, and value generation strategies. The number at the end of each line is the index of the property across the various indexes (source code).

Model:
  EntityType: Blog
    Properties:
      BlogId (int) Required PK ReadOnlyAfterSave ValueGenerated.OnAdd 0 0 0 -1 0
      Url (string) 1 1 -1 -1 -1
    Navigations:
      Posts (<Posts>k__BackingField, List<Post>) Collection ToDependent Post Inverse: Blog 0 -1 1 -1 -1
    Keys:
      BlogId PK
    Annotations:
      Relational:TableName: Blogs
      RelationshipDiscoveryConvention:NavigationCandidates: System.Collections.Immutable.ImmutableSortedDictionary`2[System.Reflection.PropertyInfo,System.Type]
  EntityType: Post
    Properties:
      PostId (int) Required PK ReadOnlyAfterSave ValueGenerated.OnAdd 0 0 0 -1 0
      BlogId (int) Required FK Index 1 1 1 -1 1
      Content (string) MaxLength4000 2 2 -1 -1 -1
        Annotations:
          MaxLength: 4000
      IsDeleted (no field, bool) Shadow Required 3 3 -1 0 -1
        Annotations:
          SqlServer:ColumnName: _IsDeleted
      Title (string) 4 4 -1 -1 -1
    Navigations:
      Blog (<Blog>k__BackingField, Blog) ToPrincipal Blog Inverse: Posts 0 -1 2 -1 -1
    Keys:
      PostId PK
    Foreign keys:
      Post {'BlogId'} -> Blog {'BlogId'} ToDependent: Posts ToPrincipal: Blog
    Annotations:
      Relational:TableName: Posts
      RelationshipDiscoveryConvention:NavigationCandidates: System.Collections.Immutable.ImmutableSortedDictionary`2[System.Reflection.PropertyInfo,System.Type]
Annotations:
  ProductVersion: 2.0.0-preview1-24937
  SqlServer:ValueGenerationStrategy: IdentityColumn

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?