13

I have started to face this issue just recently. I'm using the Visual Studio 2022 Preview latest. I made a few simple changes to the DB and used the validation tool in dbForge Studio 2022 for SQL Server to validate all objects. The DB is valid.

When I try to update my context, I get the following output.

Build started...
Build succeeded.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpDbContextGenerator.TransformText()
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpModelGenerator.ProcessTemplate(ITextTransformation transformation)
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpModelGenerator.GenerateModel(IModel model, ModelCodeGenerationOptions options)
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineerScaffolder.ScaffoldModel(String connectionString, DatabaseModelFactoryOptions databaseOptions, ModelReverseEngineerOptions modelOptions, ModelCodeGenerationOptions codeOptions)
   at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String outputContextDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, String modelNamespace, String contextNamespace, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluralize)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, String modelNamespace, String contextNamespace, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluralize)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Object reference not set to an instance of an object.

I get a successful build, but it immediately fails with the error. I'd like to research this, but no other log windows show any errors, and I cannot figure out what is causing this.

DoomerDGR8
  • 4,840
  • 6
  • 43
  • 91
  • I think the source for `TransformText()` can be found [here](https://github.com/dotnet/efcore/blob/main/src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs#L30)... but good luck trying to determine what could be null in this method. Looks like the blame for the file reveals _some_ changes were made to it within the last few months, so maybe something is broken in it. Might be worth logging an issue on that GitHub repository. – Timothy G. Nov 06 '22 at 01:32
  • This severely misses a [mre]. Check that all tools and packages are updated to the latest version. – Guru Stron Nov 06 '22 at 10:06
  • @GuruStron cannot do a minimal as this happened because there was no change except for some simplification in DB. If `Scaffold-DbContext` is a part of `dotnet-ef`, it has been updated. I'm on the `7.0.0‑rc.2.22472.11` Project, Nugets, EF, .Net and the dotnet-ef – DoomerDGR8 Nov 06 '22 at 21:07
  • I thought a `datetime2` was the cause, but that is still not it. Is there a way to get some more debug dump to troubleshoot? – DoomerDGR8 Nov 07 '22 at 04:09

4 Answers4

10

It happens because of missing PK.

You have 2 options to manage this problem:

  1. Discover the table that don't have PK by using the script (in SQL):
  select tab.[name]
  from sys.tables tab
  left outer join sys.indexes pk
  on tab.object_id = pk.object_id 
  and pk.is_primary_key = 1
  where pk.object_id is null

and add them PK

  1. Generate EF without the tables that don't have PK by using this script (in SQL)
 SELECT name
 FROM sys.tables
 where name in ( 
    select tab.[name] 
    from sys.tables tab
    left outer join sys.indexes pk
    on tab.object_id = pk.object_id 
    and pk.is_primary_key = 1
    where pk.object_id is not  null
)

then you can Scaffold DbContext from selected tables of an existing database

Patrick McDonald
  • 64,141
  • 14
  • 108
  • 120
Naomi Messing
  • 638
  • 6
  • 18
4

ok - it seems this is a known issue with EFCore 7.0.0, see Github Issue

It's caused by a missing Primary Key on a table. I found one of my tables had the PK missing, I added one and the dbcontext scaffolding then succeeded.

Rich Freeman
  • 1,009
  • 2
  • 9
  • 22
2

With Entity Framework Core 7.0.2 . Find list of tables what has not Primary key

SELECT 
    schema_name(tab.schema_id) AS [schema_name], tab.[name] AS table_name
FROM 
     sys.tables tab LEFT OUTER JOIN sys.indexes pk ON tab.object_id = pk.object_id AND pk.is_primary_key = 1
WHERE 
    pk.object_id IS NULL
ORDER BY 
    schema_name(tab.schema_id), tab.[name]

then add primary key.

Or use Entity Framework Core 6.x .

Vy Do
  • 46,709
  • 59
  • 215
  • 313
  • what happens with intersect tables that do not need a PK? I have a load of those and I don't want to have to create PKs on all of those – Adam Hey Jan 23 '23 at 21:36
  • In Entity Framework Core 7.0.2 (current version) table must have PK. Wait about 16 days more, in Entity Framework Core 7.0.3 no need PK. Intersect table that do not need a PK, you join use keywords `JOIN` and `WHERE foo.X = bar.X` as normal. – Vy Do Jan 24 '23 at 04:23
  • What a joke! The NHibernate system I'm migrating from did this 10 years ago! I recommended EF and this is making me look like an idiot – Adam Hey Jan 24 '23 at 14:51
  • Or wait to Entity Framework Core 7.0.3 after about 15 more days. It is a bug. – Vy Do Jan 24 '23 at 16:22
  • Apparently not a bug. I received a working configuration from a Microsoft engineer on the EFCore git repo. I posted my problem and solution here https://stackoverflow.com/questions/75186741/entity-framework-7-many-to-many-intersect-table-skip-navigation-problem/75247297#75247297 – Adam Hey Jan 26 '23 at 14:52
  • I also did the same think with you. Wait about more 14 days to Entity Framework Core 7.0.3 you no need this action. – Vy Do Jan 26 '23 at 17:02
0

After much aimless struggle, I finally decided to go undo my schema changes one by one and the moment I deleted this table from the DB, scaffolding started to work normally again:

CREATE TABLE [dbo].[LookupImportBrand] (
    [CompanyId] BIGINT          NOT NULL,
    [BranchId]  BIGINT          NOT NULL,
    [Name]      [dbo].[Name250] NOT NULL,
    [Active]    [dbo].[Boolean] NOT NULL,
    CONSTRAINT [FK_LookupImportBrand_LookupImportCompany] FOREIGN KEY ([CompanyId]) REFERENCES [dbo].[LookupImportCompany] ([Id])
);

I cannot pinpoint whats the root cause here but I recreated the table and all is well.

DoomerDGR8
  • 4,840
  • 6
  • 43
  • 91