Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架强制转换异常:EF尝试在SaveChangesAsync强制转换DB属性_C#_Entity Framework_Sql Server 2012_Entity Framework Core_Asp.net Core 2.0 - Fatal编程技术网

C# 实体框架强制转换异常:EF尝试在SaveChangesAsync强制转换DB属性

C# 实体框架强制转换异常:EF尝试在SaveChangesAsync强制转换DB属性,c#,entity-framework,sql-server-2012,entity-framework-core,asp.net-core-2.0,C#,Entity Framework,Sql Server 2012,Entity Framework Core,Asp.net Core 2.0,我正在尝试从ASP.NET Core(2.0)应用程序将数据保存到数据库(MS SQL 2012),但我尝试更新数据库中的一个表时出错 我已经使用EntityFrameworkCore(2.1.2)生成了运行save操作的DB上下文。当我尝试保存对用户表的更改时,应用程序崩溃,出现以下异常: 更新条目时出错。有关详细信息,请参见内部异常 内部的例外是: 无法将“System.String”类型的对象强制转换为“System.Int32”类型 我用来保存数据的代码是: using(var cont

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

我已经使用EntityFrameworkCore(2.1.2)生成了运行save操作的DB上下文。当我尝试保存对用户表的更改时,应用程序崩溃,出现以下异常:

更新条目时出错。有关详细信息,请参见内部异常

内部的例外是:

无法将“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;
    }
GetPasswordResetWithInfifeenMinutesAsync()返回的模型如下所示:

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; }
}
用户模型代码为:

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对象中删除除id和电子邮件之外的所有属性,然后运行更新,但我仍然得到相同的异常。)

这是怎么做的
GetPasswordResetWithInfifeenMinutesAsync
它得到了一个“时间对象”来自数据库,其中包含用户请求更改密码的时间以及该密码所指向的用户(以便我们可以验证它是否在最长15分钟前,如果是,则它将返回时间对象,我们将继续进行用户更新,然后从数据库中删除时间对象)如果您对该位(以及相应的
context.Remove()
)进行注释,该方法是否有效?不,我会得到相同的异常。好的,我会记录原始sql并检查它,例如
protected override void onconfig(DbContextOptionsBuilder optionsBuilder){var lf=new LoggerFactory();lf.AddConsole();base.on配置(optionBuilder);optionBuilder.EnableSensitiveDataLogging(true)。UseLoggerFactory(lf);}
(或以连接数据库上下文的方式)
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");
});
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