Asp.net mvc 突然从entityframework获取异常

Asp.net mvc 突然从entityframework获取异常,asp.net-mvc,entity-framework,azure,asp.net-identity,azure-sql-database,Asp.net Mvc,Entity Framework,Azure,Asp.net Identity,Azure Sql Database,我时常会遇到这样的例外情况: 无法将“用户”上的“电子邮件”属性设置为“System.Int64”值。必须将此属性设置为“System.String”类型的非空值。方法消息:,LogException:System.InvalidOperationException:“用户”上的“电子邮件”属性无法设置为“System.Int64”值。必须将此属性设置为“System.String”类型的非空值。 位于System.Data.Entity.Core.Common.Internal.Materia

我时常会遇到这样的例外情况:

无法将“用户”上的“电子邮件”属性设置为“System.Int64”值。必须将此属性设置为“System.String”类型的非空值。方法消息:,LogException:System.InvalidOperationException:“用户”上的“电子邮件”属性无法设置为“System.Int64”值。必须将此属性设置为“System.String”类型的非空值。 位于System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader
1.GetValue(DbDataReader,Int32序数)
lambda_法(闭合、整形器)
位于System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func
2 constructEntityDelegate、EntityKey、EntitySet EntityKey) lambda_法(闭合、整形器) 位于System.Data.Entity.Core.Common.Internal.Materialization.Coordinator
1.ReadNextElement(Shaper-Shaper)
在System.Data.Entity.Core.Common.Internal.Materialization.Shaper中
位于System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1源)
位于Project.Services.UserService.FindById(Int64 userId)

我正在MVC项目中使用Asp.net标识

我的用户类类似于:

public class User : IdentityUser<long, IdentityConfig.UserLogin, IdentityConfig.UserRole, IdentityConfig.UserClaim>
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(IdentityConfig.CustomUserManager manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        // Add custom user claims here
        return userIdentity;
    }

    [MaxLength(256)]
    [Index(IsUnique = true)]
    [Required]
    public override string Email { get; set; }

    [Required]
    [MaxLength(256)]
    public string FirstName { get; set; }

      // rest of properties
    ....
}
公共类用户:IdentityUser
{
公共异步任务GenerateUserIdentityAsync(IdentityConfig.CustomUserManager)
{
//注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配
var userIdentity=wait manager.CreateIdentityAsync(这是DefaultAuthenticationTypes.ApplicationOkie);
//在此处添加自定义用户声明
返回用户身份;
}
[最大长度(256)]
[索引(IsUnique=true)]
[必需]
公共重写字符串Email{get;set;}
[必需]
[最大长度(256)]
公共字符串名{get;set;}
//其余物业
....
}
用户管理器:

public class CustomUserManager : UserManager<User, long>
    {
        public CustomUserManager(IUserStore<User, long> store, IdentityFactoryOptions<CustomUserManager> options) : base(store)
        {
            this.UserValidator = new UserValidator<User, long>(this)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            PasswordValidator = new PasswordValidator
            {
                RequiredLength = 8,
                RequireLowercase = true,
                RequireUppercase = true,
                RequireDigit = true
            };

            // Configure user lockout defaults
            UserLockoutEnabledByDefault = true;
            DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            RegisterTwoFactorProvider("Google Authentication", new GoogleAuthenticatorTokenProvider());

            var provider = new MachineKeyProtectionProvider();
            UserTokenProvider = new DataProtectorTokenProvider<User,long>(provider.Create("ResetPasswordPurpose"));

        }
    }
公共类CustomUserManager:UserManager { 公共CustomUserManager(IUserStore商店,IdentityFactoryOptions选项):基本(商店) { this.UserValidator=新的UserValidator(this) { AllowOnlyAlphanumericUserNames=false, RequireUniqueEmail=true }; //配置密码的验证逻辑 PasswordValidator=新的PasswordValidator { 所需长度=8, RequireLowercase=true, RequireUppercase=true, RequireDigit=true }; //配置用户锁定默认值 UserLockoutEnabledByDefault=true; DefaultAccountLockoutTimeSpan=TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout=5; //注册双因素身份验证提供商。此应用程序使用电话和电子邮件作为接收验证用户代码的步骤 //您可以编写自己的提供者并将其插入此处。 RegisterWofactorProvider(“谷歌认证”,新的GoogleAuthenticatorTokenProvider()); var provider=new MachineKeyProtectionProvider(); UserTokenProvider=新的DataProtectorTokenProvider(provider.Create(“ResetPasswordPurpose”); } }
用户服务:

public class UserService : EntityService<User>, IUserService
   {
    private readonly IdentityConfig.CustomUserManager _userManager;

    public UserService(MyDbContext context, IdentityConfig.CustomUserManager userManager) : base(context)
    {
        _userManager = userManager;
    }

   public User FindById(long userId)
    {
        return _userManager.Users.FirstOrDefault(x => x.Id == userId);
    }

// other methods..
}
public类UserService:EntityService,IUserService
{
私有只读标识Config.CustomUserManager\u userManager;
公共用户服务(MyDbContext上下文,IdentityConfig.CustomUserManager用户管理器):基本(上下文)
{
_userManager=userManager;
}
公共用户FindById(长用户ID)
{
返回_userManager.Users.FirstOrDefault(x=>x.Id==userId);
}
//其他方法。。
}
注册自动传真:

        builder.RegisterModule(new ServiceModule());
        builder.RegisterModule(new EfModule());

        builder.RegisterType<IdentityConfig.RoleStore>().As<IRoleStore<IdentityConfig.Role, long>>().InstancePerRequest();
        builder.RegisterType<IdentityConfig.CustomUserStore>().As<IUserStore<User, long>>().InstancePerRequest();
        builder.RegisterType<IdentityConfig.CustomUserManager>().AsSelf().InstancePerRequest();
        builder.RegisterType<IdentityConfig.CustomSignInManager>().AsSelf().InstancePerRequest();
        builder.RegisterType<IdentityConfig.CustomRoleManager>().AsSelf().InstancePerRequest();

        builder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication);


        builder.Register(c => new IdentityFactoryOptions<IdentityConfig.CustomUserManager>
        {
            DataProtectionProvider = new DpapiDataProtectionProvider("MyWebAppName"),
            Provider = new IdentityFactoryProvider<IdentityConfig.CustomUserManager>()
        }).InstancePerRequest();



public class ServiceModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterAssemblyTypes(Assembly.Load("Project.Services"))

                 .Where(t => t.Name.EndsWith("Service") || t.Name.EndsWith("Validator"))
                 .AsImplementedInterfaces()
                 .InstancePerLifetimeScope();
    }
}


 public class EfModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType(typeof(MyDbContext)).AsSelf().WithParameter("connectionString", ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString).InstancePerRequest();
    }
}
builder.RegisterModule(新的ServiceModule());
RegisterModule(新的EfModule());
builder.RegisterType().As().InstancePerRequest();
builder.RegisterType().As().InstancePerRequest();
builder.RegisterType().AsSelf().InstancePerRequest();
builder.RegisterType().AsSelf().InstancePerRequest();
builder.RegisterType().AsSelf().InstancePerRequest();
Register(c=>HttpContext.Current.GetOwinContext().Authentication);
builder.Register(c=>newidentityfactoryoptions
{
DataProtectionProvider=新的DpapiDataProtectionProvider(“MyWebAppName”),
Provider=新标识FactoryProvider()
}).InstancePerRequest();
公共类服务模块:模块
{
受保护的覆盖无效负载(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(Assembly.Load(“Project.Services”))
其中(t=>t.Name.EndsWith(“服务”)| | t.Name.EndsWith(“验证器”))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
}
}
公共类EfModule:Module
{
受保护的覆盖无效负载(ContainerBuilder builder)
{
builder.RegisterType(typeof(MyDbContext)).AsSelf().WithParameter(“connectionString”,ConfigurationManager.connectionString[“DefaultConnection”]).connectionString.InstancePerRequest();
}
}
我还注意到,这个错误不仅影响用户,还影响其他实体

问题是应用程序运行了一段时间,然后出现了太多此类错误,这对我来说毫无意义,让我很生气


我使用的是Azure SQL、Azure web服务、Autofac。

可能是您的cookie在某个时候变成了垃圾,或者您遇到了线程问题,它同时读取和写入cookie。我看不到任何异常处理。。。您正在使用async/await。您希望该方法做什么,以及在哪里抛出异常?@DanEsparza我发布了整个异常,当应用程序运行一段时间时出现的问题通常与EF con有关