EF trying to create new entry instead of relation

1

I have a User model, and a UserRole model. In the database, UserRole is an enumerator (visualized below). When I initialized the database, the Users table has a column UserRoleId, so I assumed that Entity Framework made the relation correctly.

However, when I try to add a user, I get an error that EF is trying to create a new entry in the UserRole table.

I don't want it to create a new entry in the UserRole table, I want a number to be inserted into the UserRoleId column of the User table that references to a Role within the UserRole table.

Error:

Microsoft.EntityFrameworkCore.Database.Command:Error: Failed executing DbCommand (2ms) [Parameters=[@p0='?' (DbType = Int32), @p1='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
INSERT INTO [UserRoles] ([Id], [Role])
VALUES (@p0, @p1);

System.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'UserRoles' when IDENTITY_INSERT is set to OFF.

UserRoles Table in DB:

ID  |  Role
==============
1   |  Viewer
2   |  Owner
3   |  Admin

Models:

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public byte[] PasswordHash { get; set; }
    public byte[] PasswordSalt { get; set; }

    public UserRole UserRole { get; set; }  //<--- THE IMPORTANT PART
    ...
}

public class UserRole
{
    public int Id { get; set; }
    public string Role { get; set; }
}
c#
entity-framework-core
asked on Stack Overflow Jun 26, 2018 by JED • edited Jun 27, 2018 by JED

1 Answer

0

As Camilo Terevinto pointed out, it's necessary to explicitly add UserRoleId to the User model. After that, Add-Migration and Update-Database, and alter the front end, the controller, and the DTO so that UserRoleId is being passed in instead of a UserRole object.

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public byte[] PasswordHash { get; set; }
    public byte[] PasswordSalt { get; set; }

    public int UserRoleId { get; set; } //<--- THE IMPORTANT PARTS
    public UserRole UserRole { get; set; }  //<--- THE IMPORTANT PARTS
    ...
}
answered on Stack Overflow Jun 27, 2018 by JED

User contributions licensed under CC BY-SA 3.0