Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NullReferenceException scaffolding when no primary key set #29516

Closed
hm2075 opened this issue Nov 9, 2022 · 24 comments
Closed

NullReferenceException scaffolding when no primary key set #29516

hm2075 opened this issue Nov 9, 2022 · 24 comments
Assignees
Labels
area-scaffolding closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. customer-reported Servicing-approved type-bug
Milestone

Comments

@hm2075
Copy link

hm2075 commented Nov 9, 2022

upgraded a dotnet app from 6 to 7 with efcore updated to 7

unable to scaffold

dotnet-ef dbcontext scaffold

Entity Framework Core .NET Command-line Tools 7.0.0

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)
@ErikEJ
Copy link
Contributor

ErikEJ commented Nov 9, 2022

Which provider?
Can you share your database schema?
Can you share your .csproj?

@hm2075
Copy link
Author

hm2075 commented Nov 9, 2022

MS-sql

ADMIN	10	dbo
ADMIT	11	dbo
ARCHIVE	6	dbo
AUDIT	8	dbo
BDS	18	dbo
CORE	17	dbo
db_accessadmin	16385	db_accessadmin
db_backupoperator	16389	db_backupoperator
db_datareader	16390	db_datareader
db_datawriter	16391	db_datawriter
db_ddladmin	16387	db_ddladmin
db_denydatareader	16392	db_denydatareader
db_denydatawriter	16393	db_denydatawriter
db_owner	16384	db_owner
db_securityadmin	16386	db_securityadmin
dbo	1	dbo
DIM	5	dbo
DISCHARGE	20	dbo
GROUP	15	dbo
guest	2	guest
HangFire	22	dbo
History	19	dbo
INFORMATION_SCHEMA	3	INFORMATION_SCHEMA
Logs	7	dbo
NPR	16	dbo
PAS	13	dbo
REFERRAL	21	dbo
REPORTING	23	dbo
STANDARD	12	dbo
sys	4	sys
TOKENS	9	dbo
TRACKER	14	dbo
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>
    <IncludeOpenAPIAnalyzers>true</IncludeOpenAPIAnalyzers>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile>bin\Debug\netcoreapp2.0\Backend.xml</DocumentationFile>
    <NoWarn>1701;1702;1591</NoWarn>
    <LangVersion>9.0</LangVersion>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <LangVersion>9.0</LangVersion>
  </PropertyGroup>
  <PropertyGroup>
  <EnableNETAnalyzers>true</EnableNETAnalyzers>
  <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
  <CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors>
</PropertyGroup>
  <PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
<PropertyGroup>
 <IncludeOpenAPIAnalyzers>true</IncludeOpenAPIAnalyzers>
</PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AspNetCore.HealthChecks.Hangfire" Version="6.0.1-rc2.1" />
    <PackageReference Include="AspNetCore.HealthChecks.Oracle" Version="5.0.1" />
    <PackageReference Include="AspNetCore.HealthChecks.Redis" Version="6.0.1-rc2.2" />
    <PackageReference Include="AspNetCore.HealthChecks.SignalR" Version="6.0.1-rc2.1" />
    <PackageReference Include="AspNetCore.HealthChecks.SqlServer" Version="6.0.1-rc2.7" />
    <PackageReference Include="AspNetCore.HealthChecks.UI" Version="6.0.1-rc2.4" />
    <PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="6.0.1-rc2.4" />
    <PackageReference Include="AspNetCore.HealthChecks.UI.Core" Version="6.0.1-rc2.4" />
    <PackageReference Include="AspNetCore.HealthChecks.UI.SqlServer.Storage" Version="6.0.1-rc2.4" />
    <PackageReference Include="Dapper" Version="2.0.30" />
    <PackageReference Include="DinkToPdf" Version="1.0.8" />
    <PackageReference Include="EasyCaching.Core" Version="1.4.1" />
    <PackageReference Include="EasyCaching.Redis" Version="1.4.1" />
    <PackageReference Include="EFCoreSecondLevelCacheInterceptor" Version="3.2.0" />
    <PackageReference Include="Elastic.Apm.NetCoreAll" Version="1.11.1" />
    <PackageReference Include="EvoPdf.WordToPdf" Version="7.1.0" />
    <PackageReference Include="Hangfire.Dashboard.Basic.Authentication" Version="5.0.0" />
    <PackageReference Include="Hangfire.Dashboard.BasicAuthorization" Version="1.0.2" />
    <PackageReference Include="itext7.pdfhtml" Version="2.1.6" />
    <PackageReference Include="iTextSharp.LGPLv2.Core" Version="1.6.1" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0" />
    <PackageReference Include="Microsoft.AspNetCore.OData" Version="7.5.11" />
    <PackageReference Include="Microsoft.AspNetCore.Owin" Version="7.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.MessagePack" Version="5.0.9" />
    <PackageReference Include="Microsoft.AspNetCore.SignalR.StackExchangeRedis" Version="6.0" />
    <PackageReference Include="Microsoft.Data.SqlClient" Version="5.0.1" />
    <PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="3.1.6" />

    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0" />
    <PackageReference Include="automapper" Version="9.0.0" />
    <PackageReference Include="Exceptionless.AspNetCore" Version="4.3.2027" />
    <PackageReference Include="Matterhook.NET.MatterhookClient" Version="1.4.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.0">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="5.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="5.0.0" />
    <PackageReference Include="Microsoft.IO.RecyclableMemoryStream" Version="1.3.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0" />
    <PackageReference Include="MySql.Data" Version="8.0.30" />
    <PackageReference Include="MySqlConnector" Version="2.1.13" />
    <PackageReference Include="nHapi.Core" Version="2.6.0.2" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
    <PackageReference Include="NLog" Version="4.6.8" />
    <PackageReference Include="Oracle.ManagedDataAccess.Core" Version="3.21.3" />
    <PackageReference Include="RestSharp" Version="106.6.10" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="SimpleImpersonation" Version="3.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.1" />
    <PackageReference Include="System.Collections.Immutable" Version="6.0" />
    <PackageReference Include="System.Data.SqlClient" Version="4.8.5" />
    <PackageReference Include="System.DirectoryServices.AccountManagement" Version="4.7.0" />
    <PackageReference Include="System.Drawing.Common" Version="5.0" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.25.0" />
    <PackageReference Include="System.Reactive.Linq" Version="5.0.0" />
    <PackageReference Include="System.Reactive.Core" Version="5.0.0" />
    <PackageReference Include="NETCore.MailKit" Version="2.0.2" />
    <PackageReference Include="TimePeriodLibrary.NET" Version="2.1.1" />
    <PackageReference Include="Hangfire.Core" Version="1.7.26" />
    <PackageReference Include="Hangfire.SqlServer" Version="1.7.26" />
    <PackageReference Include="Hangfire.AspNetCore" Version="1.7.26" />
    <PackageReference Include="ServiceStack.HttpClient" Version="6.0.2" />
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Exceptionless" />
  </ItemGroup>
  <ItemGroup>
    <Content Update="nlog.config" CopyToOutputDirectory="Always" />
  </ItemGroup>
  <ItemGroup>
	<Content Include="TrainingMaterial\**">
		<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
	</Content>
</ItemGroup>
  <ItemGroup>
  </ItemGroup>
<ItemGroup>
      <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
      <DotNetCliToolReference Include="Microsoft.Dotnet.Xdt.Tools" Version="2.0.0" />
  </ItemGroup>
  <Target Name="ApplyXdtConfigTransform" BeforeTargets="_TransformWebConfig">
   <PropertyGroup>
     <_SourceWebConfig>$(MSBuildThisFileDirectory)Web.config</_SourceWebConfig>
     <_XdtTransform>$(MSBuildThisFileDirectory)Web.$(Configuration).config</_XdtTransform>
     <_TargetWebConfig>$(PublishDir)Web.config</_TargetWebConfig>
   </PropertyGroup>
   <Exec Command="dotnet transform-xdt --xml &quot;$(_SourceWebConfig)&quot; --transform &quot;$(_XdtTransform)&quot; --output &quot;$(_TargetWebConfig)&quot;" Condition="Exists('$(_XdtTransform)')" />
</Target>


</Project>

@ErikEJ
Copy link
Contributor

ErikEJ commented Nov 9, 2022

Thanks, I meant "CREATE" scripts for you database schema (tables, foreign keys)

@hm2075
Copy link
Author

hm2075 commented Nov 9, 2022

im going to try and scaffold each schema seperately, not entirely sure about create scripts, theres about 200+ tables

@ajcvickers
Copy link
Member

@hm2075 Can you also post the full output from running the command with the --verbose option?

@hm2075
Copy link
Author

hm2075 commented Nov 9, 2022

narrowed it down to a table, it didnt have an identity column set !

@ErikEJ
Copy link
Contributor

ErikEJ commented Nov 9, 2022

Can you share the CREATE TABLE script for the table causing the issue?

@hm2075
Copy link
Author

hm2075 commented Nov 10, 2022

the table that caused the issue

USE [NPR_Production]
GO

/****** Object:  Table [DISCHARGE].[tbl_discharge_Visit]    Script Date: 10/11/2022 08:16:15 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [DISCHARGE].[tbl_discharge_Visit](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TrackerID] [int] NOT NULL,
	[HospitalNumber] [varchar](50) NULL,
	[LastUpdateDT] [datetime2](7) NULL,
	[EventDT] [datetime2](7) NULL,
	[PatientClass] [varchar](50) NULL,
	[PatientLocation] [bigint] NULL,
	[PatientLocationDesc] [varchar](500) NULL,
	[VisitNumber] [varchar](50) NULL,
	[VisitNumberUnique] [varchar](50) NOT NULL,
	[AdmissionType] [varchar](50) NULL,
	[AdmissionTypeDesc] [varchar](500) NULL,
	[PreAdmitNumber] [varchar](50) NULL,
	[PriorPatientLocation] [varchar](50) NULL,
	[AttendingDoctor] [bigint] NULL,
	[ReferringDoctor] [bigint] NULL,
	[ConsultingDoctor] [bigint] NULL,
	[ConsultingDoctorDesc] [varchar](500) NULL,
	[ConsultingDoctorGMC] [varchar](500) NULL,
	[Speciality] [varchar](50) NULL,
	[SpecialtityDesc] [varchar](500) NULL,
	[ReadmissionIndicator] [varchar](50) NULL,
	[AdmitSource] [varchar](50) NULL,
	[AdmitSourceDesc] [varchar](500) NULL,
	[AdmittingDoctor] [bigint] NULL,
	[CourtesyCode] [varchar](50) NULL,
	[DischargeDisposition] [varchar](50) NULL,
	[DischargeDispositionDesc] [varchar](500) NULL,
	[DischargedtoLocation] [varchar](50) NULL,
	[DischargedtoLocationDesc] [varchar](500) NULL,
	[AccountStatus] [varchar](50) NULL,
	[AdmitDT] [datetime2](7) NULL,
	[DischargeDT] [datetime2](7) NULL,
	[AccomodationCode] [varchar](50) NULL,
	[AdmitReason] [nvarchar](4000) NULL,
	[VisitUserCode] [varchar](50) NULL,
	[ExpectedAdmitDT] [datetime2](7) NULL,
	[VisitDescription] [varchar](50) NULL,
	[ReferralSourceCode] [varchar](50) NULL,
	[ReferralSourceDesc] [varchar](500) NULL,
	[VisitPriorityCode] [varchar](50) NULL,
	[ModeofArrivalCode] [varchar](50) NULL,
	[EventType] [varchar](50) NULL,
	[action1] [varchar](50) NULL,
	[OperatorID] [varchar](50) NULL,
	[DeleteFlag] [bit] NULL
) ON [PRIMARY]
GO

ALTER TABLE [DISCHARGE].[tbl_discharge_Visit] ADD  CONSTRAINT [DF_tbl_discharge_Visit_DeleteFlag]  DEFAULT ((0)) FOR [DeleteFlag]
GO

ALTER TABLE [DISCHARGE].[tbl_discharge_Visit]  WITH NOCHECK ADD  CONSTRAINT [FK_tbl_discharge_Visit_tbl_tracker_Referral] FOREIGN KEY([TrackerID])
REFERENCES [TRACKER].[tbl_tracker_Referral] ([ID])
GO

ALTER TABLE [DISCHARGE].[tbl_discharge_Visit] CHECK CONSTRAINT [FK_tbl_discharge_Visit_tbl_tracker_Referral]
GO


@ErikEJ
Copy link
Contributor

ErikEJ commented Nov 10, 2022

it didnt have an identity column set !

[ID] [int] IDENTITY(1,1) NOT NULL,

I am confused ... did you mean primary key?

@hm2075
Copy link
Author

hm2075 commented Nov 10, 2022

yes, you are correct , i meant primary key

the differences are

with exception

USE [NPR_Production]
GO

/****** Object:  Table [DISCHARGE].[tbl_discharge_Visit]    Script Date: 10/11/2022 10:55:55 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [DISCHARGE].[tbl_discharge_Visit](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TrackerID] [int] NOT NULL,
	[HospitalNumber] [varchar](50) NULL,
	[LastUpdateDT] [datetime2](7) NULL,
	[EventDT] [datetime2](7) NULL,
	[PatientClass] [varchar](50) NULL,
	[PatientLocation] [bigint] NULL,
	[PatientLocationDesc] [varchar](500) NULL,
	[VisitNumber] [varchar](50) NULL,
	[VisitNumberUnique] [varchar](50) NOT NULL,
	[AdmissionType] [varchar](50) NULL,
	[AdmissionTypeDesc] [varchar](500) NULL,
	[PreAdmitNumber] [varchar](50) NULL,
	[PriorPatientLocation] [varchar](50) NULL,
	[AttendingDoctor] [bigint] NULL,
	[ReferringDoctor] [bigint] NULL,
	[ConsultingDoctor] [bigint] NULL,
	[ConsultingDoctorDesc] [varchar](500) NULL,
	[ConsultingDoctorGMC] [varchar](500) NULL,
	[Speciality] [varchar](50) NULL,
	[SpecialtityDesc] [varchar](500) NULL,
	[ReadmissionIndicator] [varchar](50) NULL,
	[AdmitSource] [varchar](50) NULL,
	[AdmitSourceDesc] [varchar](500) NULL,
	[AdmittingDoctor] [bigint] NULL,
	[CourtesyCode] [varchar](50) NULL,
	[DischargeDisposition] [varchar](50) NULL,
	[DischargeDispositionDesc] [varchar](500) NULL,
	[DischargedtoLocation] [varchar](50) NULL,
	[DischargedtoLocationDesc] [varchar](500) NULL,
	[AccountStatus] [varchar](50) NULL,
	[AdmitDT] [datetime2](7) NULL,
	[DischargeDT] [datetime2](7) NULL,
	[AccomodationCode] [varchar](50) NULL,
	[AdmitReason] [nvarchar](4000) NULL,
	[VisitUserCode] [varchar](50) NULL,
	[ExpectedAdmitDT] [datetime2](7) NULL,
	[VisitDescription] [varchar](50) NULL,
	[ReferralSourceCode] [varchar](50) NULL,
	[ReferralSourceDesc] [varchar](500) NULL,
	[VisitPriorityCode] [varchar](50) NULL,
	[ModeofArrivalCode] [varchar](50) NULL,
	[EventType] [varchar](50) NULL,
	[action1] [varchar](50) NULL,
	[OperatorID] [varchar](50) NULL,
	[DeleteFlag] [bit] NULL
) ON [PRIMARY]
GO

ALTER TABLE [DISCHARGE].[tbl_discharge_Visit] ADD  CONSTRAINT [DF_tbl_discharge_Visit_DeleteFlag]  DEFAULT ((0)) FOR [DeleteFlag]
GO

ALTER TABLE [DISCHARGE].[tbl_discharge_Visit]  WITH NOCHECK ADD  CONSTRAINT [FK_tbl_discharge_Visit_tbl_tracker_Referral] FOREIGN KEY([TrackerID])
REFERENCES [TRACKER].[tbl_tracker_Referral] ([ID])
GO

ALTER TABLE [DISCHARGE].[tbl_discharge_Visit] CHECK CONSTRAINT [FK_tbl_discharge_Visit_tbl_tracker_Referral]
GO




without exception

USE [NPR_Development]
GO

/****** Object:  Table [DISCHARGE].[tbl_discharge_Visit]    Script Date: 10/11/2022 10:57:21 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [DISCHARGE].[tbl_discharge_Visit](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TrackerID] [int] NOT NULL,
	[HospitalNumber] [varchar](50) NULL,
	[LastUpdateDT] [datetime2](7) NULL,
	[EventDT] [datetime2](7) NULL,
	[PatientClass] [varchar](50) NULL,
	[PatientLocation] [bigint] NULL,
	[PatientLocationDesc] [varchar](500) NULL,
	[VisitNumber] [varchar](50) NULL,
	[VisitNumberUnique] [varchar](50) NOT NULL,
	[AdmissionType] [varchar](50) NULL,
	[AdmissionTypeDesc] [varchar](500) NULL,
	[PreAdmitNumber] [varchar](50) NULL,
	[PriorPatientLocation] [varchar](50) NULL,
	[AttendingDoctor] [bigint] NULL,
	[ReferringDoctor] [bigint] NULL,
	[ConsultingDoctor] [bigint] NULL,
	[ConsultingDoctorDesc] [varchar](500) NULL,
	[ConsultingDoctorGMC] [varchar](500) NULL,
	[Speciality] [varchar](50) NULL,
	[SpecialtityDesc] [varchar](500) NULL,
	[ReadmissionIndicator] [varchar](50) NULL,
	[AdmitSource] [varchar](50) NULL,
	[AdmitSourceDesc] [varchar](500) NULL,
	[AdmittingDoctor] [bigint] NULL,
	[CourtesyCode] [varchar](50) NULL,
	[DischargeDisposition] [varchar](50) NULL,
	[DischargeDispositionDesc] [varchar](500) NULL,
	[DischargedtoLocation] [varchar](50) NULL,
	[DischargedtoLocationDesc] [varchar](500) NULL,
	[AccountStatus] [varchar](50) NULL,
	[AdmitDT] [datetime2](7) NULL,
	[DischargeDT] [datetime2](7) NULL,
	[AccomodationCode] [varchar](50) NULL,
	[AdmitReason] [nvarchar](4000) NULL,
	[VisitUserCode] [varchar](50) NULL,
	[ExpectedAdmitDT] [datetime2](7) NULL,
	[VisitDescription] [varchar](50) NULL,
	[ReferralSourceCode] [varchar](50) NULL,
	[ReferralSourceDesc] [varchar](500) NULL,
	[VisitPriorityCode] [varchar](50) NULL,
	[ModeofArrivalCode] [varchar](50) NULL,
	[EventType] [varchar](50) NULL,
	[action1] [varchar](50) NULL,
	[OperatorID] [varchar](50) NULL,
	[Deprecated] [bit] NOT NULL,
	[CreatedUsername] [nvarchar](100) NOT NULL,
	[CreatedDT] [datetime] NOT NULL,
	[UpdatedUsername] [nvarchar](100) NOT NULL,
	[UpdatedDT] [datetime] NOT NULL,
	[DeleteFlag] [bit] NOT NULL,
 CONSTRAINT [PK_tbl_discharge_Visit] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [DISCHARGE].[tbl_discharge_Visit] ADD  CONSTRAINT [DF_tbl_discharge_Visit_Deprecated]  DEFAULT ((0)) FOR [Deprecated]
GO

ALTER TABLE [DISCHARGE].[tbl_discharge_Visit] ADD  CONSTRAINT [DF_tbl_discharge_Visit_DeleteFlag]  DEFAULT ((0)) FOR [DeleteFlag]
GO

ALTER TABLE [DISCHARGE].[tbl_discharge_Visit]  WITH CHECK ADD  CONSTRAINT [FK_tbl_discharge_Visit_tbl_tracker_Referral] FOREIGN KEY([TrackerID])
REFERENCES [TRACKER].[tbl_tracker_Referral] ([ID])
GO

ALTER TABLE [DISCHARGE].[tbl_discharge_Visit] CHECK CONSTRAINT [FK_tbl_discharge_Visit_tbl_tracker_Referral]
GO




@aldrashan
Copy link

Same issue here for a table with no PK's.
Also using SQL Server.

@ErikEJ
Copy link
Contributor

ErikEJ commented Nov 10, 2022

@aldrashan are you able to create a full repro and share it? (Just the CREATE scripts)

@aldrashan
Copy link

@aldrashan are you able to create a full repro and share it? (Just the CREATE scripts)

/****** Object:  Table [dbo].[AspNetUserRoles]    Script Date: 10/11/2022 16:16:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[AspNetUserRoles](
	[UserId] [nvarchar](36) NOT NULL,
	[RoleId] [nvarchar](36) NOT NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_AspNetUserRoles_AspNetRoles_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[AspNetRoles] ([Id])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_AspNetUserRoles_AspNetRoles_RoleId]
GO

ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_AspNetUserRoles_AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_AspNetUserRoles_AspNetUsers_UserId]
GO

Setting a PK (UserId, RoleId) fixes the problem.

@ErikEJ
Copy link
Contributor

ErikEJ commented Nov 10, 2022

@aldrashan I think we need scripts for the related tables also

@titouancreach
Copy link

Added PK solved the problem for me too. This is the query I used to find the table without 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]

@aldrashan
Copy link

/****** Object:  Table [dbo].[ScaffoldingTest2]    Script Date: 14/11/2022 8:27:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[ScaffoldingTest2](
	[Id] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_ScaffoldingTest2] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO


/****** Object:  Table [dbo].[ScaffoldingTest]    Script Date: 14/11/2022 8:27:15 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[ScaffoldingTest](
	[Id] [uniqueidentifier] NOT NULL,
	[Description] [nvarchar](500) NOT NULL,
	[ScaffoldingTest2Id] [uniqueidentifier] NOT NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[ScaffoldingTest]  WITH CHECK ADD  CONSTRAINT [FK_ScaffoldingTest_ScaffoldingTest2] FOREIGN KEY([ScaffoldingTest2Id])
REFERENCES [dbo].[ScaffoldingTest2] ([Id])
GO

ALTER TABLE [dbo].[ScaffoldingTest] CHECK CONSTRAINT [FK_ScaffoldingTest_ScaffoldingTest2]
GO

Minimum example to replicate the issue.
Scaffolding these 2 tables causes the error.

@ErikEJ
Copy link
Contributor

ErikEJ commented Nov 14, 2022

@aldrashan Thanks a lot!

@ajcvickers
Copy link
Member

@bricelam We should consider patching this.

@ajcvickers ajcvickers changed the title EFcore 7 scaffolding exception NullReferenceException scaffolding when no primary key set Nov 15, 2022
@ajcvickers
Copy link
Member

Note from triage: we should prepare a patch for this.

@bricelam
Copy link
Contributor

bricelam commented Dec 5, 2022

🩹 Workaround

You can work around this by using custom templates and adding a null check to DbContext.t4 line 219:

<#= foreignKey.PrincipalToDependent != null ? $"p => p.{foreignKey.PrincipalToDependent.Name}" : "" #>

@bricelam
Copy link
Contributor

bricelam commented Dec 5, 2022

Using --data-annotations should also work around it.

bricelam added a commit to bricelam/efcore that referenced this issue Dec 5, 2022
@Jacko1394

This comment was marked as resolved.

@ajcvickers

This comment was marked as resolved.

@Yip-Yip
Copy link

Yip-Yip commented Dec 4, 2023

I had the same error on code first with

builder.Property(u => u.CurrentUserId).HasColumnType("bigint");

When the table was string see currentuserid

public abstract class EntityBase : IEquatable<Entity>
//where TId : struct
{
protected TId _id;
public TId Id { get => _id;
set
{
// operator== EqualityComparer
if (!EqualityComparer.Default.Equals(_id, value))
{
_id = value;
}
} }

 //for db and user track
 [Timestamp]
 public byte[] RowVersion { get; set; }

 public string CurrentUserId { get; set; }


 public DateTime CreateDate { get; set; }

 public DateTime? LastModified { get; set; }


 protected EntityBase(TId id, string currentUserId)
 {
     CurrentUserId = currentUserId;
     Id = id;
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-scaffolding closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. customer-reported Servicing-approved type-bug
Projects
None yet
Development

No branches or pull requests

8 participants