I am started with .NET Core 3.0 and add ASP.NET Core identity. In tbl_SYS_AspNet_UserRoles there is no primary key.

I scaffold dbcontext and model for another tables in database, using Entity Framework Core tools reference - .NET CLI and Entity Framework generates e.HasNoKey() method in model builder for tbl_SYS_AspNet_UserRoles. I also read doc from Microsoft Documentation .
But when I run the project and query for data from another table dbcontext generate , an error:
_'The navigation '' cannot be added because it targets the keyless entity type 'tbl_SYS_AspNet_UserRoles'. Navigations can only target entity types with keys.'_
EF Core version:Microsoft.EntityFrameworkCore Version="3.0.0"
Database provider: Microsoft.EntityFrameworkCore.SqlServer Version="3.0.0"
Target framework: .NET Core 3.0
IDE: Visual Studio Comunity 2019 16.3.5
Full reference of other Asp.Net Core Identity and Entityframework
Microsoft.AspNetCore.Identity Version="2.2.0"
Microsoft.AspNetCore.Identity.EntityFrameworkCore Version="3.0.0"
Microsoft.EntityFrameworkCore Version="3.0.0"
Microsoft.EntityFrameworkCore.Design Version="3.0.0"
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore Version="3.0.0"
Microsoft.EntityFrameworkCore.SqlServer Version="3.0.0"
Microsoft.EntityFrameworkCore.Tools Version="3.0.0"
Microsoft.Extensions.Configuration.Json Version="3.0.0"
Microsoft.Extensions.DependencyInjection.Abstractions Version="3.0.0"
Microsoft.IdentityModel.Tokens Version="5.5.0"
You cannot mix version 2 and 3! Update Ms.AspnetCore.Identity
Ok ,Thanks for reply .But latest version of AspNetCore.Identity is 2.2 and I devlop my application in .Net Core 3.0 ,so should I wait until AspNetCore.Identity 3.0?
Currently I add a fake Identity column in tbl_SYS_AspNet_UserRoles to solve the problem temporarily.
Please suggest me if I am doing wrong.
You should read the upgrade guide!
https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#remove-obsolete-package-references
Asper your advice I change .csproj like bellow
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="AutoMapper" Version="9.0.0" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.0.0" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="5.5.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc4" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="5.0.0-rc4" />
<PackageReference Include="Swashbuckle.AspNetCore.Filters" Version="5.0.0-rc8" />
<PackageReference Include="Swashbuckle.AspNetCore.ReDoc" Version="5.0.0-rc4" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.5.0" />
</ItemGroup>
</Project>
EF scaffolding generate bellow code for tbl_SYS_AspNet_UserRoles
modelBuilder.Entity<tbl_SYS_AspNet_UserRoles>(entity =>
{
entity.HasNoKey();
entity.HasIndex(e => e.PK_RoleID)
.HasName("IX_AspNetUserRoles_RoleId");
entity.HasOne(d => d.PK_Role)
.WithMany(p => p.tbl_SYS_AspNet_UserRoles)
.HasForeignKey(d => d.PK_RoleID)
.HasConstraintName("FK_AspNetUserRoles_AspNetRoles_RoleId");
entity.HasOne(d => d.PK_User)
.WithMany(p => p.tbl_SYS_AspNet_UserRoles)
.HasForeignKey(d => d.PK_UserID)
.HasConstraintName("FK_AspNetUserRoles_AspNetUsers_UserId");
});
But getting the exception still

@ikuntalb
In tbl_SYS_AspNet_UserRoles there is no primary key.
That table should have a composite key, and indeed you show an image with the two columns that make up the composite key. Can you provide more details on what you mean by, "no primary key?"
hi @ajcvickers
Thanks for reply .Yes this is true this table have composite key ,but EF scaffolder generated code through an exception as shown in above image.For more details I will try to make simple project to replicate this ,may be today or tomorrow .
Thanks
@ikuntalb Ah! I see--thanks for the additional information.
@ErikEJ I tried scaffolding on the command line for the default Identity database and got this:
```C#
modelBuilder.Entity
{
entity.HasKey(e => new { e.UserId, e.RoleId });
entity.HasIndex(e => e.RoleId);
entity.HasOne(d => d.Role)
.WithMany(p => p.AspNetUserRoles)
.HasForeignKey(d => d.RoleId);
entity.HasOne(d => d.User)
.WithMany(p => p.AspNetUserRoles)
.HasForeignKey(d => d.UserId);
});
``
which seems correct and doesn't includeHasNoKey`. Is it possible this is an issue with the Power Tools?
No, not likely. The Power Tools does not influence this at all. I guess the user has been modifying the dB schema by hand, but if we could see a full create SQL script from the scaffolded database?
Thanks @ErikEJ
@ikuntalb We are not able to reproduce this using the default schema for ASP.NET Core Identity. If you have changed the schema and removed the primary key, then that would cause what you are seeing, but then this would be correct because the model requires that primary key to work correctly.
Hi @ErikEJ and @ajcvickers
Thanks for your taughts and comment,yes I change table name and column name but as I can remember I am not change any relation or remove any primary key ,I will check my code again and make a sample if it reproduce the same error I will definitely revert with sample.
Thanks for your valuable time and suggestion .
Renaming table/column names in database requires you to update references. So likely you need to drop the PK to rename the column. You would also need to recreate it afterwards.
Hi all
Bellow is my custom .net core identity DB script and EF genarated context and its still genarate bellow code for tbl_SYS_AspNet_UserRoles
USE [aspnetcore_identity_test]
GO
/****** Object: Table [dbo].[tbl_SYS_AspNet_RoleClaims] Script Date: 10/22/2019 7:44:38 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_SYS_AspNet_RoleClaims](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FK_RoleID] [int] NOT NULL,
[ClaimType] [nvarchar](max) NULL,
[ClaimValue] [nvarchar](max) NULL,
CONSTRAINT [PK_AspNetRoleClaims] 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] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[tbl_SYS_AspNet_Roles] Script Date: 10/22/2019 7:44:38 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_SYS_AspNet_Roles](
[PK_RoleID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](256) NULL,
[NormalizedName] [nvarchar](256) NULL,
[ConcurrencyStamp] [nvarchar](max) NULL,
CONSTRAINT [PK_AspNetRoles] PRIMARY KEY CLUSTERED
(
[PK_RoleID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[tbl_SYS_AspNet_UserClaims] Script Date: 10/22/2019 7:44:38 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_SYS_AspNet_UserClaims](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FK_UserID] [int] NOT NULL,
[ClaimType] [nvarchar](max) NULL,
[ClaimValue] [nvarchar](max) NULL,
CONSTRAINT [PK_AspNetUserClaims] 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] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[tbl_SYS_AspNet_UserInformation] Script Date: 10/22/2019 7:44:38 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_SYS_AspNet_UserInformation](
[PK_UserID] [int] IDENTITY(1,1) NOT NULL,
[FK_UserID_CreatedBy] [int] NULL,
[FK_DateKey_CreatedOn] [int] NULL,
[FK_TimeKey_CreatedOn] [int] NULL,
[IsDeleted] [bit] NULL,
[IsActive] [bit] NULL,
[FK_UserID_ModifiedBy] [int] NULL,
[FK_DateKey_ModifiedOn] [int] NULL,
[FK_TimeKey_ModifiedOn] [int] NULL,
[FK_ClientID] [int] NULL,
[UserName] [nvarchar](256) NULL,
[NormalizedUserName] [nvarchar](256) NULL,
[Email] [nvarchar](256) NULL,
[NormalizedEmail] [nvarchar](256) NULL,
[EmailConfirmed] [bit] NOT NULL,
[PasswordHash] [nvarchar](max) NULL,
[SecurityStamp] [nvarchar](max) NULL,
[ConcurrencyStamp] [nvarchar](max) NULL,
[PhoneNumber] [nvarchar](max) NULL,
[PhoneNumberConfirmed] [bit] NOT NULL,
[TwoFactorEnabled] [bit] NOT NULL,
[LockoutEnd] [datetimeoffset](7) NULL,
[LockoutEnabled] [bit] NOT NULL,
[AccessFailedCount] [int] NOT NULL,
[Password] [varchar](20) NULL,
[Title] [varchar](50) NULL,
[FirstName] [varchar](100) NULL,
[MiddleName] [varchar](100) NULL,
[LastName] [varchar](100) NULL,
[Gender] [varchar](20) NULL,
[MobileNo] [varchar](20) NULL,
[DisplayUserName] [varchar](150) NULL,
[UserImagePath] [varchar](500) NULL,
[IsSuperAdmin] [bit] NULL,
[Latitude] [varchar](50) NULL,
[Longitude] [varchar](50) NULL,
[Device_UUID] [varchar](50) NULL,
CONSTRAINT [PK_AspNetUsers] PRIMARY KEY CLUSTERED
(
[PK_UserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[tbl_SYS_AspNet_UserLogins] Script Date: 10/22/2019 7:44:38 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_SYS_AspNet_UserLogins](
[LoginProvider] [nvarchar](128) NOT NULL,
[ProviderKey] [nvarchar](128) NOT NULL,
[ProviderDisplayName] [nvarchar](max) NULL,
[FK_UserID] [int] NOT NULL,
CONSTRAINT [PK_AspNetUserLogins] PRIMARY KEY CLUSTERED
(
[LoginProvider] ASC,
[ProviderKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[tbl_SYS_AspNet_UserRoles] Script Date: 10/22/2019 7:44:38 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_SYS_AspNet_UserRoles](
[PK_UserID] [int] NOT NULL,
[PK_RoleID] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[tbl_SYS_AspNet_UserTokens] Script Date: 10/22/2019 7:44:38 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_SYS_AspNet_UserTokens](
[UserId] [int] NOT NULL,
[LoginProvider] [nvarchar](128) NOT NULL,
[Name] [nvarchar](128) NOT NULL,
[Value] [nvarchar](max) NULL,
CONSTRAINT [PK_AspNetUserTokens] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[LoginProvider] ASC,
[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserInformation] ADD CONSTRAINT [DF_tbl_SYS_AspNet_Users_FK_DateKey_CreatedOn] DEFAULT ((((rtrim(datepart(year,getdate()))+replicate('0',(2)-len(rtrim(datepart(month,getdate())))))+rtrim(datepart(month,getdate())))+replicate('0',(2)-len(rtrim(datepart(day,getdate())))))+rtrim(datepart(day,getdate()))) FOR [FK_DateKey_CreatedOn]
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserInformation] ADD CONSTRAINT [DF_tbl_SYS_AspNet_Users_FK_TimeKey_CreatedOn] DEFAULT ((datepart(hour,getdate())*(3600)+datepart(minute,getdate())*(60))+datepart(second,getdate())) FOR [FK_TimeKey_CreatedOn]
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserInformation] ADD CONSTRAINT [DF_tbl_SYS_AspNet_Users_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserInformation] ADD CONSTRAINT [DF_tbl_SYS_AspNet_Users_IsActive] DEFAULT ((1)) FOR [IsActive]
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_RoleClaims] WITH CHECK ADD CONSTRAINT [FK_AspNetRoleClaims_AspNetRoles_RoleId] FOREIGN KEY([FK_RoleID])
REFERENCES [dbo].[tbl_SYS_AspNet_Roles] ([PK_RoleID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_RoleClaims] CHECK CONSTRAINT [FK_AspNetRoleClaims_AspNetRoles_RoleId]
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserClaims] WITH CHECK ADD CONSTRAINT [FK_AspNetUserClaims_AspNetUsers_UserId] FOREIGN KEY([FK_UserID])
REFERENCES [dbo].[tbl_SYS_AspNet_UserInformation] ([PK_UserID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserClaims] CHECK CONSTRAINT [FK_AspNetUserClaims_AspNetUsers_UserId]
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserLogins] WITH CHECK ADD CONSTRAINT [FK_AspNetUserLogins_AspNetUsers_UserId] FOREIGN KEY([FK_UserID])
REFERENCES [dbo].[tbl_SYS_AspNet_UserInformation] ([PK_UserID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserLogins] CHECK CONSTRAINT [FK_AspNetUserLogins_AspNetUsers_UserId]
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserRoles] WITH CHECK ADD CONSTRAINT [FK_AspNetUserRoles_AspNetRoles_RoleId] FOREIGN KEY([PK_RoleID])
REFERENCES [dbo].[tbl_SYS_AspNet_Roles] ([PK_RoleID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserRoles] CHECK CONSTRAINT [FK_AspNetUserRoles_AspNetRoles_RoleId]
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserRoles] WITH CHECK ADD CONSTRAINT [FK_AspNetUserRoles_AspNetUsers_UserId] FOREIGN KEY([PK_UserID])
REFERENCES [dbo].[tbl_SYS_AspNet_UserInformation] ([PK_UserID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserRoles] CHECK CONSTRAINT [FK_AspNetUserRoles_AspNetUsers_UserId]
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserTokens] WITH CHECK ADD CONSTRAINT [FK_AspNetUserTokens_AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[tbl_SYS_AspNet_UserInformation] ([PK_UserID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tbl_SYS_AspNet_UserTokens] CHECK CONSTRAINT [FK_AspNetUserTokens_AspNetUsers_UserId]
GO
modelBuilder.Entity<tbl_SYS_AspNet_UserRoles>(entity =>
{
entity.HasNoKey();
entity.HasOne(d => d.PK_Role)
.WithMany(p => p.tbl_SYS_AspNet_UserRoles)
.HasForeignKey(d => d.PK_RoleID)
.HasConstraintName("FK_AspNetUserRoles_AspNetRoles_RoleId");
entity.HasOne(d => d.PK_User)
.WithMany(p => p.tbl_SYS_AspNet_UserRoles)
.HasForeignKey(d => d.PK_UserID)
.HasConstraintName("FK_AspNetUserRoles_AspNetUsers_UserId");
});
Please point me where I am doing wrong.
You are not creating a primary key for tbl_SYS_AspNet_UserRoles!
@ErikEJ If we have a table with no primary key for whatsoever reason, how will this work? I see lot of System.InvalidOperationException: 'The navigation '' cannot be added because it targets the keyless entity type ''. Navigations can only target entity types with keys.'
Same as : https://github.com/aspnet/EntityFrameworkCore/issues/18633 ???
You are not creating a primary key for tbl_SYS_AspNet_UserRoles!
Sorry @ErikEJ, are you meaning we need to remove the entity.HasNoKey(); line?
@enricobenedos No, I am talking about your SQL script
I had the same problem here. These are my codes:
[...]
public partial class Radusergroup
{
public string Username { get; set; }
public string Groupname { get; set; }
public int Priority { get; set; }
}
[...]
[...]
modelBuilder.Entity<Radusergroup>(entity =>
{
entity.HasNoKey();
entity.ToTable("radusergroup");
entity.HasIndex(e => e.Username)
.HasName("username");
entity.Property(e => e.Groupname)
.IsRequired()
.HasColumnName("groupname")
.HasMaxLength(64)
.HasDefaultValueSql("''''''");
entity.Property(e => e.Priority)
.HasColumnName("priority")
.HasColumnType("int(11)")
.HasDefaultValueSql("'1'");
entity.Property(e => e.Username)
.IsRequired()
.HasColumnName("username")
.HasMaxLength(64)
.HasDefaultValueSql("''''''");
});
[...]
As @ErikEJ said, you are not creating a key for your table. He is right, however, sometimes, you can't change the database for some reason. In my case, this is a database which another application uses, so I don't want to compromise that other application, so my solution was simply turn my attribute "username" into a key, like this:
public partial class Radusergroup
{
[Key]
public string Username { get; set; }
public string Groupname { get; set; }
public int Priority { get; set; }
}
and remove the HasNoKey on your context:
[...]
modelBuilder.Entity<Radusergroup>(entity =>
{
//entity.HasNoKey();
entity.ToTable("radusergroup");
entity.HasIndex(e => e.Username)
.HasName("username");
entity.Property(e => e.Groupname)
.IsRequired()
.HasColumnName("groupname")
.HasMaxLength(64)
.HasDefaultValueSql("''''''");
entity.Property(e => e.Priority)
.HasColumnName("priority")
.HasColumnType("int(11)")
.HasDefaultValueSql("'1'");
entity.Property(e => e.Username)
.IsRequired()
.HasColumnName("username")
.HasMaxLength(64)
.HasDefaultValueSql("''''''");
});
[...]
That will probably solve it.
Most helpful comment
You are not creating a primary key for tbl_SYS_AspNet_UserRoles!