C# – Trying to set a non-null string to type ‘System.Int32’

cef-code-firstentity-frameworkentity-framework-migrations

Entity Framework is throwing this exception:

The 'PasswordIterations' property on 'BranchIdentity' could not be set to a 'System.String' value. You must set this property to a non-null value of type 'System.Int32'.

It's throwing on this line:

// Validate uniqueness or email and username
var user = sqlStorage.BranchIdentities.FirstOrDefault(i => i.Username.ToLower() == viewModel.Username.ToLower());

The exception only throws when there is an entity that matches the query. If there are no matches, the exception isn't thrown.

My BranchIdentity model:

namespace Branch.Models.Sql
{
    public class BranchIdentity
    {
        [Key]
        public int Id { get; set; }

        [Required]
        public string Username { get; set; }

        [Required]
        public string PasswordHash { get; set; }

        [Required]
        public string PasswordSalt { get; set; }

        [Required]
        public int PasswordIterations { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        public string FullName { get; set; }

        public virtual ICollection<BranchIdentitySession> BranchIdentitySessions { get; set; } 

        public virtual BranchRole BranchRole { get; set; }

        public virtual GamerIdentity GamerIdentity { get; set; }
    }
}

And my schema (taken from the sql database) – auto-generated using code-first migrations:

CREATE TABLE [dbo].[BranchIdentities] (
    [Id]                 INT            IDENTITY (1, 1) NOT NULL,
    [Username]           NVARCHAR (MAX) NOT NULL,
    [PasswordHash]       NVARCHAR (MAX) NOT NULL,
    [PasswordSalt]       NVARCHAR (MAX) NOT NULL,
    [PasswordIterations] INT            NOT NULL,
    [Email]              NVARCHAR (MAX) NOT NULL,
    [BranchRole_Id]      INT            NULL,
    [GamerIdentity_Id]   INT            NULL,
    [FullName]           NVARCHAR (MAX) DEFAULT ('') NOT NULL,
    CONSTRAINT [PK_dbo.BranchIdentities] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_dbo.BranchIdentities_dbo.BranchRoles_BranchRole_Id] FOREIGN KEY ([BranchRole_Id]) REFERENCES [dbo].[BranchRoles] ([Id]),
    CONSTRAINT [FK_dbo.BranchIdentities_dbo.GamerIdentities_GamerIdentity_Id] FOREIGN KEY ([GamerIdentity_Id]) REFERENCES [dbo].[GamerIdentities] ([Id])
);

I have tried making PasswordIterations nullable, but to no avail.

Best Answer

Sounds like your schema and the Entity don't match up, You posted your Code first generated code but that might have changed since the table was created. take a look at the table in SQL Server Manager and double check the data type for that column.

Related Topic