我正在尝试从我的ASP.NET Core(2.0)应用程序将数据保存到我的数据库(MS SQL 2012),但是当我尝试更新其数据时,我的数据库中的一个表给了我一个错误 .

我使用Entity Framework Core(2.1.2)来生成运行保存操作的DB上下文 . 当我尝试将更改保存到User表时,应用程序崩溃时出现以下异常:

更新条目时发生错误 . 有关详细信息,请参阅内部异常

内在的例外:

无法将类型为“System.String”的对象强制转换为“System.Int32” .

我用来保存数据的代码是:

using(var context = new DBContext())
    {
        var user = null;
        var passwordReset = await GetPasswordResetWithinFifteenMinutesAsync(id);

        if (passwordReset != null)
        {
            user = await context.Users
                                .Where(u => u.Id == passwordReset.FkUser)
                                .FirstOrDefaultAsync();

            user.Password = password;
            context.Remove(passwordReset);
            await context.SaveChangesAsync(); //This is where the app crashes
        }
        return user?.ToUserModel() ?? null;
    }

GetPasswordResetWithinFifteenMinutesAsync()返回的模型如下所示:

public partial class PartnerPasswordreset
{
    public int PkId { get; set; }
    public int FkUser { get; set; }
    public Guid RequestId { get; set; }
    public DateTime TimeReset { get; set; }

    public Users FkUserNavigation { get; set; }
}

Users模型代码是:

public partial class Users
{
    public Users()
    {
        CustomerTurnoverPotentialFkCreatedByUser = new HashSet<CustomerTurnoverPotential>();
        CustomerTurnoverPotentialFkUpdatedByUser = new HashSet<CustomerTurnoverPotential>();
        KeyValues = new HashSet<KeyValues>();
        Salespersons = new HashSet<Salespersons>();
        SupplierUsers = new HashSet<SupplierUsers>();
        UserAddresses = new HashSet<UserAddresses>();
        UserCustomers = new HashSet<UserCustomers>();
        UserSuppliers = new HashSet<UserSuppliers>();
        PartnerLeadComments = new HashSet<PartnerLeadComments>();
        PartnerPasswordreset = new HashSet<PartnerPasswordreset>();
        PartnerUserFormAccess = new HashSet<PartnerUserFormAccess>();
    }

    public int Id { get; set; }
    public DateTime CreatedDate { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public int? PackageId { get; set; }
    public DateTime? BirthDate { get; set; }
    public int? CampaignId { get; set; }
    public string PasswordResetCode { get; set; }
    public bool ReceiveNewsLetter { get; set; }
    public int? CrmUserId { get; set; }
    public bool? TermsAccepted { get; set; }
    public bool DataStorageConsentFb { get; set; }
    public bool MarketingUsageConsentFb { get; set; }
    public bool DataStorageConsentFa { get; set; }
    public bool MarketingUsageConsentFa { get; set; }

    public CustomerCampaign Campaign { get; set; }
    public Packages Package { get; set; }
    public ICollection<CustomerTurnoverPotential> CustomerTurnoverPotentialFkCreatedByUser { get; set; }
    public ICollection<CustomerTurnoverPotential> CustomerTurnoverPotentialFkUpdatedByUser { get; set; }
    public ICollection<KeyValues> KeyValues { get; set; }
    public ICollection<Salespersons> Salespersons { get; set; }
    public ICollection<SupplierUsers> SupplierUsers { get; set; }
    public ICollection<UserAddresses> UserAddresses { get; set; }
    public ICollection<UserCustomers> UserCustomers { get; set; }
    public ICollection<UserSuppliers> UserSuppliers { get; set; }
    public ICollection<PartnerLeadComments> PartnerLeadComments { get; set; }
    public ICollection<PartnerPasswordreset> PartnerPasswordreset { get; set; }
    public ICollection<PartnerUserFormAccess> PartnerUserFormAccess { get; set; }
    internal UserModel ToUserModel()
    {

        if (UserSuppliers == null)
        {
            return null;
        }

        var roles = new List<string>();
        var menus = new List<string>();

        foreach (var us in UserSuppliers)
        {
            roles.Add(us.FkUserRoleNavigation.Role);
            var menuAccess = us.FkUserRoleNavigation?.PartnerMenuAccess;

            foreach (var menu in menuAccess)
            {
                menus.Add($"{menu.FkPartnerMenuNavigation.Name};{menu.FkPartnerMenuNavigation.Path}");
            }
        }

        return new UserModel
        {
            UserId = Id,
            FirstName = FirstName,
            LastName = LastName,
            UserName = Email,
            Password = Password,
            Roles = roles,
            Menus = menus
        };

    }

    internal CustomerUserModel ToCustomerUserModel()
    {
        return new CustomerUserModel
        {
            FirstName = FirstName,
            LastName = LastName,
            Email = Email,
            Phone = Phone

        };
    }
}

EF生成的Users对象具有以下模型构建器:

modelBuilder.Entity<Users>(entity =>
{
    entity.HasIndex(e => e.Email)
        .HasName("UQ__Users__A9D10534165A2CA1")
        .IsUnique();

    entity.Property(e => e.Id).HasColumnName("id");

    entity.Property(e => e.BirthDate).HasColumnType("datetime");

    entity.Property(e => e.CreatedDate)
        .HasColumnType("smalldatetime")
        .HasDefaultValueSql("(getdate())");

    entity.Property(e => e.CrmUserId).HasColumnName("CrmUserID");

    entity.Property(e => e.DataStorageConsentFa).HasColumnName("DataStorageConsent_FA");

    entity.Property(e => e.DataStorageConsentFb).HasColumnName("DataStorageConsent_FB");

    entity.Property(e => e.Email)
        .IsRequired()
        .HasMaxLength(50)
        .IsUnicode(false)
        .HasDefaultValueSql("('')");

    entity.Property(e => e.FirstName)
        .IsRequired()
        .HasMaxLength(50)
        .IsUnicode(false)
        .HasDefaultValueSql("('')");

    entity.Property(e => e.LastName)
        .IsRequired()
        .HasMaxLength(50)
        .IsUnicode(false)
        .HasDefaultValueSql("('')");

    entity.Property(e => e.MarketingUsageConsentFa).HasColumnName("MarketingUsageConsent_FA");

    entity.Property(e => e.MarketingUsageConsentFb).HasColumnName("MarketingUsageConsent_FB");

    entity.Property(e => e.Password)
        .IsUnicode(false)
        .HasDefaultValueSql("('')");

    entity.Property(e => e.PasswordResetCode)
        .HasMaxLength(50)
        .IsUnicode(false);

    entity.Property(e => e.Phone)
        .IsRequired()
        .HasMaxLength(50)
        .IsUnicode(false)
        .HasDefaultValueSql("('')");

    entity.Property(e => e.TermsAccepted)
        .IsRequired()
        .HasDefaultValueSql("((1))");

    entity.HasOne(d => d.Campaign)
        .WithMany(p => p.Users)
        .HasForeignKey(d => d.CampaignId)
        .HasConstraintName("FK__Users__CampaignI__0BDC9E2E");

    entity.HasOne(d => d.Package)
        .WithMany(p => p.Users)
        .HasForeignKey(d => d.PackageId)
        .HasConstraintName("fk_Users_Packagess");
});

在编写脚本时,用户的DB表如下所示:

USE [DB]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Users](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [CreatedDate] [smalldatetime] NOT NULL,
    [FirstName] [varchar](50) NOT NULL,
    [LastName] [varchar](50) NOT NULL,
    [Phone] [varchar](50) NOT NULL,
    [Email] [varchar](50) NOT NULL,
    [Password] [varchar](max) NULL,
    [PackageId] [int] NULL,
    [BirthDate] [datetime] NULL,
    [CampaignId] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[Users] ADD [PasswordResetCode] [varchar](50) NULL
ALTER TABLE [dbo].[Users] ADD [ReceiveNewsLetter] [bit] NOT NULL
ALTER TABLE [dbo].[Users] ADD [CrmUserID] [int] NULL
ALTER TABLE [dbo].[Users] ADD [TermsAccepted] [bit] NOT NULL
ALTER TABLE [dbo].[Users] ADD [DataStorageConsent_FB] [bit] NOT NULL
ALTER TABLE [dbo].[Users] ADD [MarketingUsageConsent_FB] [bit] NOT NULL
ALTER TABLE [dbo].[Users] ADD [DataStorageConsent_FA] [bit] NOT NULL
ALTER TABLE [dbo].[Users] ADD [MarketingUsageConsent_FA] [bit] NOT NULL
 CONSTRAINT [PK_Users] 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]
UNIQUE NONCLUSTERED 
(
    [Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Users] ADD  CONSTRAINT [DF_Users_CreatedDate]  DEFAULT (getdate()) FOR [CreatedDate]
GO

ALTER TABLE [dbo].[Users] ADD  CONSTRAINT [DF_Users_FirstName]  DEFAULT ('') FOR [FirstName]
GO

ALTER TABLE [dbo].[Users] ADD  CONSTRAINT [DF_Users_LastName]  DEFAULT ('') FOR [LastName]
GO

ALTER TABLE [dbo].[Users] ADD  CONSTRAINT [DF_Users_Phone]  DEFAULT ('') FOR [Phone]
GO

ALTER TABLE [dbo].[Users] ADD  CONSTRAINT [DF_Users_Email]  DEFAULT ('') FOR [Email]
GO

ALTER TABLE [dbo].[Users] ADD  CONSTRAINT [DF_Users_Password]  DEFAULT ('') FOR [Password]
GO

ALTER TABLE [dbo].[Users] ADD  DEFAULT ((0)) FOR [ReceiveNewsLetter]
GO

ALTER TABLE [dbo].[Users] ADD  DEFAULT ((0)) FOR [TermsAccepted]
GO

ALTER TABLE [dbo].[Users] ADD  DEFAULT ((0)) FOR [DataStorageConsent_FB]
GO

ALTER TABLE [dbo].[Users] ADD  DEFAULT ((0)) FOR [MarketingUsageConsent_FB]
GO

ALTER TABLE [dbo].[Users] ADD  DEFAULT ((0)) FOR [DataStorageConsent_FA]
GO

ALTER TABLE [dbo].[Users] ADD  DEFAULT ((0)) FOR [MarketingUsageConsent_FA]
GO

ALTER TABLE [dbo].[Users]  WITH CHECK ADD FOREIGN KEY([CampaignId])
REFERENCES [dbo].[CustomerCampaign] ([id])
GO

ALTER TABLE [dbo].[Users]  WITH CHECK ADD  CONSTRAINT [fk_Users_Packagess] FOREIGN KEY([PackageId])
REFERENCES [dbo].[Packages] ([id])
GO

ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [fk_Users_Packagess]
GO

我猜测EF生成的内容和数据库的实际结构之间存在不匹配,但我找不到它 . 有任何想法吗?

(我也尝试从Users对象中删除所有属性,除了id和Email,然后运行更新,但我仍然得到相同的异常 . )