Git Product home page Git Product logo

entityframeworkcore.generator's People

Contributors

dattaproffs avatar dependabot-preview[bot] avatar dependabot[bot] avatar hamedsabzian avatar pacoweb avatar pwelter34 avatar shusen avatar sucrose0413 avatar tjackadams avatar vinod-vetrivel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

entityframeworkcore.generator's Issues

bug: null exception when have generation.yml file

I used efg initialize -c <ConnectionString> to generated generation.yml file.
Then run efg generate -c <ConnectionString>
It always throw exception:

 F Host terminated unexpectedly
System.NullReferenceException: Object reference not set to an instance of an object.
   at EntityFrameworkCore.Generator.ModelGenerator.IsIgnored[TOption](Entity entity, TOption options, SharedModelOptions sharedOptions) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\ModelGenerator.cs:line 616
   at EntityFrameworkCore.Generator.ModelGenerator.CreateModel[TOption](Entity entity, TOption options, ModelType modelType) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\ModelGenerator.cs:line 409
   at EntityFrameworkCore.Generator.ModelGenerator.GetModels(Entity entity) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\ModelGenerator.cs:line 383
   at EntityFrameworkCore.Generator.ModelGenerator.Generate(GeneratorOptions options, DatabaseModel databaseModel, IRelationalTypeMappingSource typeMappingSource) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\ModelGenerator.cs:line 70
   at EntityFrameworkCore.Generator.CodeGenerator.Generate(GeneratorOptions options) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\CodeGenerator.cs:line 47
   at EntityFrameworkCore.Generator.GenerateCommand.OnExecute(CommandLineApplication application) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\GenerateCommand.cs:line 76
--- End of stack trace from previous location where exception was thrown ---
   at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.Invoke(MethodInfo method, Object instance, Object[] arguments)
   at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.OnExecute(ConventionContext context, CancellationToken cancellationToken)
   at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.<>c__DisplayClass0_0.<<Apply>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at McMaster.Extensions.CommandLineUtils.CommandLineApplication.ExecuteAsync(String[] args, CancellationToken cancellationToken)
   at McMaster.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
   at EntityFrameworkCore.Generator.Program.Main(String[] args) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\Program.cs:line 50

Without generation.yml, it work normaly

Config Documentation: Model Views and Joined Tables

I may have simply missed this in the documentation, but I'm having a hard time figuring out what my configuration file would look like if I wanted to create an entity of multiple tables joined via interconnecting foreign keys in sql server? Can you point me in the direction of some examples?

Kind Regards.

Table in two schemas error

I have this database structure

CREATE TABLE [dbo].[TableCompany](
[IdCompany] [int] NOT NULL,
[CompanyName] nchar NULL,
CONSTRAINT [PK_TableCompany] PRIMARY KEY CLUSTERED
(
[IdCompany] ASC
)) ON [PRIMARY]

GO

CREATE TABLE [Schema1].[TableCompany](
[IdCompany] [int] NOT NULL,
[CompanyName] nchar NULL,
CONSTRAINT [PK_TableCompany] PRIMARY KEY CLUSTERED
(
[IdCompany] ASC
)) ON [PRIMARY]

GO

And that is my configuration file
database:
tables:
- TableCompany
schemas:
- dbo

The program generate 2 entities TableCompany and TableCompany1. One for each schema.
I expected the generation of just only one entity for the schema dbo.

Sqlite Error due to schema null

When I try to generate code for an SQLite database, the process terminates at the model generation of first table. As the schema is null, the regex fails in the ToLegalName function. Below is the part of the log where it fails.

19:56:43 I Loaded database model for: data
19:56:43 I Building code generation model from database: data
19:56:43 D   Processing Table : null.Logs
19:56:43 F Host terminated unexpectedly
System.ArgumentNullException: Value cannot be null. (Parameter 'input')
   at System.Text.RegularExpressions.Regex.IsMatch(String input)
   at System.Text.RegularExpressions.Regex.IsMatch(String input, String pattern)
   at EntityFrameworkCore.Generator.ModelGenerator.ToLegalName(String name) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\ModelGenerator.cs:line 603
   at EntityFrameworkCore.Generator.ModelGenerator.Generate(GeneratorOptions options, DatabaseModel databaseModel, IRelationalTypeMappingSource typeMappingSource) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\ModelGenerator.cs:line 75
   at EntityFrameworkCore.Generator.CodeGenerator.Generate(GeneratorOptions options) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\CodeGenerator.cs:line 47
   at EntityFrameworkCore.Generator.GenerateCommand.OnExecute(CommandLineApplication application) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\GenerateCommand.cs:line 76
--- End of stack trace from previous location where exception was thrown ---
   at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.Invoke(MethodInfo method, Object instance, Object[] arguments)
   at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.OnExecute(ConventionContext context, CancellationToken cancellationToken)
   at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.<>c__DisplayClass0_0.<<Apply>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at McMaster.Extensions.CommandLineUtils.CommandLineApplication.ExecuteAsync(String[] args, CancellationToken cancellationToken)
   at McMaster.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
   at EntityFrameworkCore.Generator.Program.Main(String[] args) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\Program.cs:line 50

MySQL generate validator error

Hi,

I got the validator file empty when generate with MySQL provider.

validator:
generate: true
name: '{Model.Name}Validator'
baseClass: 'AbstractValidator<{Model.Name}>'
namespace: '{Project.Namespace}.Domain.{Entity.Name}.Validation'
directory: '{Project.Directory}\Domain{Entity.Name}\Validation'
document: true

Cheers

Feature: Stored Procedure

This could be an enhancement or a feature,

Scripting from Yml file was awesome. and thank you for giving us a clean way to script back form database. how do we include the stored procedures in the database?

generating code to call the sp's also would be great.

Thank you.
V

The specified provider 'MySQL' is not supported.

System.NotSupportedException: The specified provider 'MySQL' is not supported.
at EntityFrameworkCore.Generator.CodeGenerator.GetDatabaseModelFactory() in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\CodeGenerator.cs:line 285
at EntityFrameworkCore.Generator.CodeGenerator.Generate(GeneratorOptions options) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\CodeGenerator.cs:line 41
at EntityFrameworkCore.Generator.GenerateCommand.OnExecute(CommandLineApplication application) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\GenerateCommand.cs:line 76
--- End of stack trace from previous location where exception was thrown ---
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.Invoke(MethodInfo method, Object instance, Object[] arguments)
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.OnExecute(ConventionContext context)
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.<>c__DisplayClass0_0.<b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at McMaster.Extensions.CommandLineUtils.CommandLineApplication.<>c__DisplayClass142_0.b__0()
at McMaster.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at EntityFrameworkCore.Generator.Program.Main(String[] args) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\Program.cs:line 50

Add support for multiple DbContext-classes

I'm using efg to generate two different DbContexts, one regular read/write and a second one for read only access.

For this I have two separate .yml-configuration files and I run using efg -f standard-context.yml

The problem is that when I do this, the generator finds the read only DbContext first, and tries to rename it to the standard context name.

I Rename Context Class'PmMarknadSyncDbContext' to 'MarknadReadOnlyDbContext'.

My solution today is to do the generation outside of my project folder and the manually replace the files. But then I loose changes I made outside of #region

Generator fails when connectionstring contains curly braces

I had a connectionstring with a password with curly braces, for example:

connectionSTring: 'Data Source=host;Initial Catalog=database; User ID=username;Password=pass}'

Executing the tool results in the following stacktrace:

12:21:43 I Loading options file: generation.yml 12:21:43 I Loading database model ... 12:21:43 F Host terminated unexpectedly System.FormatException: One of the identified items was in an invalid format. at EntityFrameworkCore.Generator.VariableDictionary.Eval(String variableOrText, ISet1 loop) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\VariableDictionary.cs:line 182
at EntityFrameworkCore.Generator.VariableDictionary.Get(String name) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\VariableDictionary.cs:line 62
at EntityFrameworkCore.Generator.CodeGenerator.ResolveConnectionString(DatabaseOptions database) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\CodeGenerator.cs:line 258
at EntityFrameworkCore.Generator.CodeGenerator.GetDatabaseModel(IDatabaseModelFactory factory) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\CodeGenerator.cs:line 248
at EntityFrameworkCore.Generator.CodeGenerator.Generate(GeneratorOptions options) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\CodeGenerator.cs:line 41
at EntityFrameworkCore.Generator.GenerateCommand.OnExecute(CommandLineApplication application) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\GenerateCommand.cs:line 76
--- End of stack trace from previous location where exception was thrown ---
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.Invoke(MethodInfo method, Object instance, Object[] arguments)
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.OnExecute(ConventionContext context)
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.<>c__DisplayClass0_0.<b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at McMaster.Extensions.CommandLineUtils.CommandLineApplication.<>c__DisplayClass142_0.b__0()
at EntityFrameworkCore.Generator.Program.Main(String[] args) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\Program.cs:line 50`

The problem is solved by changing the curly brace to a double curly brace.

Error running efg on Solus linux: "version GLIBC_PRIVATE not defined in file ld-linux-x86-64.so.2 with link time reference"

Hi there.

I am using Solus linux, along with Core 3 preview 2 and VS Code. I am using the dotnet snap package. It installs fine from the terminal, but throws and error when I try to run efg. Let me know if there is any other info I may need to provide about my environment.

$ dotnet tool install --global EntityFrameworkCore.Generator --version 1.0.0.36
You can invoke the tool using the following command: efg
Tool 'entityframeworkcore.generator' (version '1.0.0.36') was successfully installed.

$ efg
efg: relocation error: /usr/lib/libc.so.6: symbol _dl_exception_create, version GLIBC_PRIVATE not defined in file ld-linux-x86-64.so.2 with link time reference
$ code-oss --version
1.32.0
48ffb9a4e0d60339a158e57b56a6c1bbf31368a4
x64
.NET Core SDK (reflecting any global.json):
 Version:   3.0.100-preview-010184
 Commit:    c57bde4593

Runtime Environment:
 OS Name:     solus
 OS Version:  3.9999
 OS Platform: Linux
 RID:         linux-x64
 Base Path:   /snap/dotnet-sdk/28/sdk/3.0.100-preview-010184/

Host (useful for support):
  Version: 3.0.0-preview-27324-5
  Commit:  63a01b08e5

.NET Core SDKs installed:
  3.0.100-preview-010184 [/snap/dotnet-sdk/28/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.App 3.0.0-preview-19075-0444 [/snap/dotnet-sdk/28/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 3.0.0-preview-27324-5 [/snap/dotnet-sdk/28/shared/Microsoft.NETCore.App]

Specify Schema folder in config

While composing the yml file we specify which schema's to use.

tables to include or empty to include all

tables:

schemas to include or empty to include all

schemas:
- Asset
- Party
- Event
- Customer
- Order
- Venues
- Ref

Now i want to specify folder per schema.

entity class file configuration

entity:
namespace: "{Project.Namespace}.{Schema}.Data.Entities" # the entity class namespace
directory: '{Project.Directory}{Schema}\Data\Entities' # the entity class output directory

is this possible or the option is to create multiple yml files and stitch the results manually.

create/update models for many-to-many relationships do not happen if either side is read-only

Scenario:

I have a role table, and a user table, and a userrole table that represents the many-to-many relationship, and I specify role as an entity to exclude via the model:create:exclude:entities and model:update:exclude:entities lists.

Expectation:

Generation would create models for create and update UserRole, since I have not excluded UserRole, just Role.

Actual:

I have to remove the excludes for Role create/update to get UserRole create/update.

It is sensible in the real world to CRUD the many-to-many relationship without CRUDing one side or the other.

Error naming Validators

Hi.. when I run efg generate, the validators classes are finishing with number one (1). This is the Validator section in my generation.yml file

validator:
generate: true
name: '{Entity.Name}Validator'
baseClass: AbstractValidator<{Model.Name}>
namespace: '{Project.Namespace}.Application.Validators'
directory: '{Project.Directory}\MyApplication.Application\Validators'

CustomerValidator1.cs
ColorValidator1.cs

Thanks for your help!

How to use efg nuget package?

Hello

I read documentation and did not found any information why we need nuget package. All samples was with using "efg" command on command line. I'm assuming that generator could be somehow used in this way? Maybe we could automate generation process with it (if not, then another question - how to automate generation process?)?

Thank you for answers!

Use martinjw/dbschemareader to read database schema

I began using this project a little bit to make a POCO + DBContext generator for at least SQL Server, Oracle, and PGSql, and saw your project which seems to be what I wanted to do, but support only SQL Server for now.

martinjw/dbschemareader supports lots of database kinds. I'm not involved in this project at all, but it seems to be a pretty feature complete project.

Furthermore, it has a compare feature which could be useful to regerenate the classes.

Disable relationship autogeneration

Hello
I met the similar problem with relationships auto generation as some other users here: relationship not correctly works when FK is different then the primary key. Overriding is the option to solve this. But, could the relationship auto generation be disabled on config file?

After removing "Generated Relationships" region on model, auto generation still adds configuration on "Map" class, but should not. This cause an error.

exclude regex not working?

we have database with a lot of tables "ref.qbo_...." (quickbooks online dumps). I wish to exclude them, cannot get this done. Tried:

  • regex: ref.qbo*
  • regex: ref.qbo*$
  • regex: ref.qbo*
  • regex: ref.qbo*$
    Nada.
    Any ideas appreciated, need to get this working. Thx

Error at EFCore 2.2

My project is run with EFCore 2.2
when I build code by Views,The Map File has a Error.There have 2 method which are not supported.

Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<TEntity>.HasNoKey
Microsoft.EntityFrameworkCore.RelationalEntityTypeBuilderExtensions.ToView

efg in Windows7?

Windows 7
I have installed:

dotnet tool install --global EntityFrameworkCore.Generator

it successfully installed.
Then:

efg
'efg' is not recognized as an internal or external command,
operable program or batch file.

Is it possible to run efg in Windows 7?

Able to exclude tables from generation

I'm having a large database that contains some tables that create issues with EF Core, I would like to be able to exclude them using the config.

What I do now is listing all the tables under database.tables and commenting away the tables I want to skip.

'efg' is not recognized as an internal or external command

I have installed EntityFrameworkCore.Generator on windows 10.
dotnet tool install --global EntityFrameworkCore.Generator

It has shown install successfully.

but I type efg --help it shown

'efg' is not recognized as an internal or external command, operable program or batch file.

Entity generation fails when the Db contains both Plural and Singular Tables

Hi, I would like to use this awesome tool to generate entities out of the Quartz's DB (its a scheduler which can store its data in the DB). When I tried to generate I got an error which is a ArgumentNullException. I decided to download the source to find what cause the problem and found that the Quartz's DB contains plural and singular table names (...imo its NOT a best practice to have mixed naming in the DB...).

The fix for this "error":
Its possible to call the .Pluralize() and .Singularize() methods as if we don't know if we have Plural or .Singular tables (because its mixed).

So in the "ModelGenerator.cs" file's private "EntityName" method can be changed as the following:
Line 535:
From "name.Pluralize();"
To "name.Pluralize(inputIsKnownToBeSingular: false);"
Line 537:
From "name.Singularize();"
To "name.Singularize(inputIsKnownToBePlural: false);"

This way it will fix the generator for DB's which have mixed naming.

Navigation Propery Name

Dear all
I like this tool as it generates entities for database views and can customize the output. the tiny issue I got when using Scaffold-DbContext for reverse engineering:
public Patent()
{
public virtual ICollection Inventors { get; set; }
}
but when generate with the generator tool, I got this:
public Patent()
{
public virtual ICollection PatentInventors { get; set; }
}

as you see the class name Patent has been concatenated to the property name, so can we have any custom way to keep only the navigation property name?

Feature: append Attributes to entity model properties

I'd like to append some validation attributes onto properties of a model class. Is it possible to append attributes something like [JsonIgnore] or some other attributes to the properties of the model class by any way?

How do you utilize the entity scripts?

My goal is to prevent 2 fields from being created when generating the entity files. I modified the .csx file with the following:

foreach (var property in Entity.Properties)
    {
        // Skip properties
        if (Entity.EntityClass == "FuelOrder")
        {
            if (property.PropertyName == "ESignature"
                || property.PropertyName == "ESignatureImage")
            {
                continue;
            }
        }

This generated a yaml file for FuelOrder without the 2 fields, however, the .cs file contained the 2 fields. What am I missing? How do I use the templates after generating them?

Remove Column Property to support for changing Database Type

Hello Loresoft,

  1. When using Code-First, it's easy to change database file: for example
  • options.UseSqlite(connectionString)
  • options.UseSqlserver(connectionString)
    2, The code generate by efg is not that flexible since:
  • efg create mapping file with db specific type such as:
    builder.Property(t => t.Id)
    .IsRequired()
    .HasColumnName("Id")
    .HasColumnType("int")
    .ValueGeneratedOnAdd();
  • The specific ColumnType is not required with entity framework, it can generate automatically based on the model fields => the needed code is only:
    builder.Property(t => t.Id)
    .IsRequired()
    .HasColumnName("Id")
    .ValueGeneratedOnAdd();
    By remove // .HasColumnType("int") our code can support to change db type again.
  1. So, Loresoft, can we have option not to generate ColumnType in our yml configuration file?
    Thank you.

Sincerely

Generattion for One to One/Zero relationship

I have table that exactly one or none relation with another table, usually with entity framrwork we can use WithOne in mapping and mark it optional, i'm using different FK than the primary key. i'm not able to have a custom mapping as it is always regenrated also the entoty is generated with one entiy in one side but a collection in the other side.

Is their a way to solve these issues ?

Exception thrown when table naming is set to plural, but the table name in the database is singular.

Just want to say a great project to start off with! I'm currently just testing it and i came across this issue.

so my generation.yml configuration contains this snippet

database:
  connectionString: <omitted>
  provider: SqlServer
  tables:
    - ReportOutputType
  tableNaming: Plural

The table naming option is set to plural, but the table name is singular. I know this is only one table, but the database we are looking to scaffold has a lot more tables and unfortunately a mix of single and plural table names (the naming convention wasn't strict....).

The exception is as follows

System.ArgumentNullException: Value cannot be null. (Parameter 'input')
at System.Text.RegularExpressions.Regex.IsMatch(String input)
at System.Text.RegularExpressions.Regex.IsMatch(String input, String pattern)
at EntityFrameworkCore.Generator.ModelGenerator.ToLegalName(String name) in C:\projects\entityframeworkcore-generator \src\EntityFrameworkCore.Generator.Core\ModelGenerator.cs:line 581
at EntityFrameworkCore.Generator.ModelGenerator.ToClassName(String tableName, String tableSchema) in C:\projects\enti tyframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\ModelGenerator.cs:line 562
at EntityFrameworkCore.Generator.ModelGenerator.CreateEntity(EntityContext entityContext, DatabaseTable tableSchema) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\ModelGenerator.cs:line 104
at EntityFrameworkCore.Generator.ModelGenerator.GetEntity(EntityContext entityContext, DatabaseTable tableSchema, Boolean processRelationships, Boolean processMethods) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\ModelGenerator.cs:line 79
at EntityFrameworkCore.Generator.ModelGenerator.Generate(GeneratorOptions options, DatabaseModel databaseModel, IRelationalTypeMappingSource typeMappingSource) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\ModelGenerator.cs:line 69
at EntityFrameworkCore.Generator.CodeGenerator.Generate(GeneratorOptions options) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\CodeGenerator.cs:line 47
at EntityFrameworkCore.Generator.GenerateCommand.OnExecute(CommandLineApplication application) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\GenerateCommand.cs:line 76
--- End of stack trace from previous location where exception was thrown ---
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.Invoke(MethodInfo method, Object instance, Object[] arguments)
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.OnExecute(ConventionContext context, CancellationToken cancellationToken)
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.<>c__DisplayClass0_0.<b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at McMaster.Extensions.CommandLineUtils.CommandLineApplication.ExecuteAsync(String[] args, CancellationToken cancellationToken)
at McMaster.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at EntityFrameworkCore.Generator.Program.Main(String[] args) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\Program.cs:line 50

I narrowed it down to this section of code, looks like its actually caused by Humanizer.

private string EntityName(string name)
{
var tableNaming = _options.Database.TableNaming;
var entityNaming = _options.Data.Entity.EntityNaming;
if (tableNaming != TableNaming.Plural && entityNaming == EntityNaming.Plural)
name = name.Pluralize();
else if (tableNaming != TableNaming.Singular && entityNaming == EntityNaming.Singular)
name = name.Singularize();
return name;
}

because the table name is already singular, humanizer returns null from the Singularize method which then carriers on and throws the exception.

Looks like the override Singularize should fix this, but i noticed there are quite a few usages of this throughout the project.

I can open a PR to update them all. Whats your thoughts?

Optimistic concurrency change needed in the sample.

I was reviewing your sample application and noticed that the Optimistic concurrency checks were not working. I was using postman to update the same entity with the original rowversion. The tracking in your sample needs a small change on the base controller . Per the URL below you need to update the original value of the rowversion otherwise you will never get a DB concurrency exception.

https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/concurrency?view=aspnetcore-2.1&tabs=visual-studio

ITrackConcurrency trackConcurrency = updateModel as ITrackConcurrency;
if (trackConcurrency != null)
{
System.Diagnostics.Debug.WriteLine("update model rowversion:" + trackConcurrency.RowVersion);
DataContext.Entry(entity).Property(nameof(ITrackConcurrency.RowVersion)).OriginalValue = Convert.FromBase64String(trackConcurrency.RowVersion);
}

Here is the full function on the EntityControllerBase

protected virtual async Task UpdateModel(Guid id, TUpdateModel updateModel, CancellationToken cancellationToken = default(CancellationToken))
{
string identityName = User?.Identity?.Name;

        updateModel.Updated = DateTimeOffset.UtcNow;
        updateModel.UpdatedBy = identityName;

        // validate model
        await UpdateValidator.ValidateAndThrowAsync(updateModel, cancellationToken: cancellationToken);

        // primary key
        object[] keyValue = new object[] { id };

        // find entity to update by id, not model id
        TEntity entity = await DataContext
            .Set<TEntity>()
            .FindAsync(keyValue, cancellationToken);

        if (entity == null)
        {
            return default(TReadModel);
        }

        // copy updates from model to entity
        Mapper.Map(updateModel, entity);

         

        ITrackConcurrency trackConcurrency = updateModel as ITrackConcurrency;
        if (trackConcurrency != null)
        {
            System.Diagnostics.Debug.WriteLine("update model rowversion:" + trackConcurrency.RowVersion);
            DataContext.Entry(entity).Property(nameof(ITrackConcurrency.RowVersion)).OriginalValue = Convert.FromBase64String(trackConcurrency.RowVersion);
        }

        try
        {
            // save updates
            await DataContext
                .SaveChangesAsync(cancellationToken);

        }
        catch (Exception ex)
        {
            string msg = ex.Message;
            throw;
        }



        // return read model
        TReadModel readModel = await ReadModel(id, cancellationToken);
        return readModel;
    }

Bug : configuration - entity - relationshipNaming : Preserve don't work

entity:
relationshipNaming: Preserve

When I set to Suffix, he "List" is well appended
When I set to Plural or don't set relationshipNaming , result is Pluralized (default)
But When I set the relationshipNaming to Preserve, result is "singularized"
previous relationShip name is not used.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.