尝试设置非空字符串以键入'System.Int32'

Ale*_*eed 11 c# entity-framework ef-code-first ef-migrations

实体框架抛出此异常:

'BranchIdentity'上的'PasswordIterations'属性无法设置为'System.String'值.您必须将此属性设置为类型为"System.Int32"的非null值.

这是在抛出这条线:

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

仅当存在与查询匹配的实体时才会抛出异常.如果没有匹配项,则不会抛出异常.

我的BranchIdentity模型:

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的架构(取自sql数据库) - 使用代码优先迁移自动生成:

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])
);
Run Code Online (Sandbox Code Playgroud)

我试过制作PasswordIterations可空,但无济于事.

小智 11

听起来像您的架构和实体不匹配,您发布了代码首先生成的代码,但自创建表以来可能已更改.查看SQL Server Manager中的表并仔细检查该列的数据类型.


Ale*_*eed 7

只是对于其他任何有这个问题的人.设置断点DatabaseContext并确保它连接到正确的数据库.我忘记了一个web.config文件覆盖了我的.