• Stars
    star
    376
  • Rank 113,810 (Top 3 %)
  • Language
    C#
  • License
    MIT License
  • Created about 6 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate Entity Framework Core model from an existing database

Overview

.NET Core command-line (CLI) tool to generate Entity Framework Core model from an existing database.

Build status

NuGet Version

Features

  • Entity Framework Core database first model generation
  • Safe regeneration via region replacement
  • Safe Renaming via mapping file parsing
  • Optionally generate read, create and update models from entity
  • Optionally generate validation and object mapper classes

Documentation

Entity Framework Core Generator documentation is available via Read the Docs

Installation

To install EntityFrameworkCore.Generator tool, run the following command in the console

dotnet tool install --global EntityFrameworkCore.Generator

After the tool has been install, the efg command line will be available. Run efg --help for command line options

Generate Command

Entity Framework Core Generator (efg) creates source code files from a database schema. To generate the files with no configuration, run the following

efg generate -c <ConnectionString>

Replace <ConnectionString> with a valid database connection string.

Generation Output

The generate command will create the follow files and directory structure by default. The root directory defaults to the current working directory. Most of the output names and locations can be customized in the configuration file

Data Context Output

The EntityFramework DbContext file will be created in the root directory.

Entities Output

The entities directory will contain the generated source file for entity class representing each table.

Mapping Output

The mapping directory contains a fluent mapping class to map each entity to its table.

Initialize Command

The initialize command is used to create the configuration yaml file and optionally set the connection string. The configuration file has many options to configure the generated output. See the configuration file documentation for more details.

The following command will create an initial generation.yaml configuration file as well as setting a user secret to store the connection string.

efg initialize -c <ConnectionString>

When a generation.yaml configuration file exists, you can run efg generate in the same directory to generate the source using that configuration file.

Regeneration

Entity Framework Core Generator supports safe regeneration via region replacement and source code parsing. A typical workflow for a project requires many database changes and updates. Being able to regenerate the entities and associated files is a huge time saver.

Region Replacement

All the templates output a region on first generation. On future regeneration, only the regions are replaced. This keeps any other changes you've made to the source file.

Example of a generated entity class

public partial class Status
{
    public Status()
    {
        #region Generated Constructor
        Tasks = new HashSet<Task>();
        #endregion
    }

    #region Generated Properties
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public int DisplayOrder { get; set; }

    public bool IsActive { get; set; }

    public DateTimeOffset Created { get; set; }

    public string CreatedBy { get; set; }

    public DateTimeOffset Updated { get; set; }

    public string UpdatedBy { get; set; }

    public Byte[] RowVersion { get; set; }
    #endregion

    #region Generated Relationships
    public virtual ICollection<Task> Tasks { get; set; }
    #endregion
}

When the generate command is re-run, the Generated Constructor, Generated Properties and Generated Relationships regions will be replace with the current output of the template. Any other changes outside those regions will be safe.

Source Parsing

In order to capture and preserve Entity, Property and DbContext renames, the generate command parses any existing mapping and DbContext class to capture how things are named. This allows you to use the full extend of Visual Studio's refactoring tools to rename things as you like. Then, when regenerating, those changes won't be lost.

Database Providers

Entity Framework Core Generator supports the following databases.

  • SQL Server
  • PostgreSQL
  • MySQL
  • Sqlite

The provider can be set via command line or via the configuration file.

Set via command line

efg generate -c <ConnectionString> -p <Provider>

Set in configuration file

database:
  connectionString: 'Data Source=(local);Initial Catalog=Tracker;Integrated Security=True'
  provider: SqlServer

Database Schema

The database schema is loaded from the metadata model factory implementation of IDatabaseModelFactory. Entity Framework Core Generator uses the implemented interface from each of the supported providers similar to how ef dbcontext scaffold works.

View Models

Entity Framework Core Generator supports generating Read, Create and Update view models from an entity. Many projects rely on view models to shape data. The model templates can be used to quickly get the basic view models created. The model templates also support regeneration so any database change can easily be sync'd to the view models.

Change Log

Version 5.0

  • add support for navigation property renames
  • update generated query methods to support CancellationToken
  • add support for temporal tables
  • add regex clean support for table and column names

Version 4.5

  • add support for nullable reference types

Version 4.0

  • upgrade projects to .net 6

Version 3.1

  • Breaking change to generated mapping constants
    • TableName is now Table.Name
    • TableSchema is now Table.Schema
    • Column{Name} is now Columns.{Name}
  • add additional automapper for read model to update model

Version 3.0

  • Add Table.Name and Table.Schema variable support in yaml configuration.
  • Add entity name option to control the name of the entity. Leave blank to use previous generate logic. Set under the entity -> name yaml settings.
  • Add exclude table support. Set under the database -> exclude yaml settings.
  • Include and Exclude expression can now be exact or regex. When exact, will be direct string match. When regex, will use regular expression to match. Default is regex for legacy support.

Version 2.5

  • Add external script template support
  • Misc bug fixes

Version 2.0

  • Add support for Entity Framework Core 3.0
  • Add provider support for PostgreSQL, MySQL and Sqlite
  • Add View support

Version 1.1

  • Add alias to commands, can use efg gen for efg generate and efg init for efg initialize
  • Fix bug where base class for Entity was placed in wrong location
  • Fix misc sorting issue that caused needless source control changes

More Repositories

1

msbuildtasks

The MSBuild Community Tasks Project is an open source project for MSBuild tasks.
C#
947
star
2

LoreSoft.Blazor.Controls

Blazor Controls
C#
121
star
3

Injectio

Source generator that helps register attribute marked services in the dependency injection ServiceCollection
C#
104
star
4

Calculator

Calculator.NET - Calculator that evaluates math expressions
C#
92
star
5

NLog.Mongo

MongoDB Target for NLog
C#
67
star
6

MongoDB.Messaging

MongoDB Messaging Library
C#
60
star
7

FluentRest

Lightweight fluent wrapper over HttpClient to make REST calls easier
C#
59
star
8

NetSpell

Spell Checker for .NET
C#
52
star
9

DataGenerator

Automatically generate data for an object
C#
51
star
10

KickStart

Application initialization helper
C#
42
star
11

EntityChange

Library to compare two object graphs detecting change
C#
36
star
12

Estimatorx

A simple project estimation application.
C#
27
star
13

MediatR.CommandQuery

CQRS framework based on MediatR
C#
23
star
14

FluentCommand

Fluent Wrapper for DbCommand
C#
17
star
15

DotNet.Property

.NET Core command-line (CLI) tool to update project properties and version numbers on build
C#
14
star
16

AutoPoco.Extensions

Additional conventions and data sources for AutoPoco.
C#
8
star
17

LoreSoft.Shared

Fast reflection library
C#
8
star
18

NLog.Xml

NLog xml layout and render
C#
7
star
19

PLINQO.EntityFramework.DbContext

Entity Framework DbContext templates for CodeSmith Generator
C#
7
star
20

MongoDB.Abstracts

MongoDB abstract repository pattern
C#
7
star
21

TypeScriptGenerator

CodeSmith Template to generate TypeScript interface for .NET a class
C#
6
star
22

NLog.Fluent

Fluent API for NLog
C#
6
star
23

InstructorIQ

Training calendar manangement
JavaScript
6
star
24

ShellTools

Windows Shell Tools
C#
4
star
25

ReflectionAccessor

Fast late bound reflection type access
C#
4
star
26

SvnTools

Backup Tool For Subversion Repositories
C#
4
star
27

PLINQO.EntityFrameworkCore

Entity Framework Core templates for CodeSmith Generator
C#
4
star
28

ServiceFramework

Processing service framework
C#
3
star
29

FluentLogger

Fluent logger abstraction as a NuGet source code package
C#
3
star
30

AspNetCore.SecurityKey

Security API Key Authentication Implementation for ASP.NET Core
C#
3
star
31

XmlFormatter

Format Xml Documents
C#
2
star
32

Cosmos.Abstracts

Cosmos DB Abstracts library defines abstract base classes for repository pattern.
C#
2
star
33

Cosmos.Identity

Cosmos DB provider for ASP.NET Core Identity framework
C#
1
star
34

mp4v2.net

Fork of MP4v2 Library for .net
1
star
35

AssemblyMetadata.Generators

Source generator to expose assembly attributes as string constants.
C#
1
star
36

FluentHtml

Fluent Html Helper for Asp.net MVC
C#
1
star
37

Blazone

Blazone is a simple authentication module for Blazor
C#
1
star
38

TableStorage.Abstracts

Azure Table Storage Abstracts library defines abstract base classes for repository pattern.
C#
1
star