突然从实体框架中获取异常



我不时会得到这个异常:

"User"的"Email"属性无法设置为"System.Int64"值。必须将此属性设置为"System.String"类型的非null值。方法消息:,LogException:System.InvalidOperationException:"User"的"Email"属性无法设置为"System.Int64"值。您必须将此属性设置为"System.String"类型的非null值。位于System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader1.GetValue(DbDataReader reader, Int32 ordinal) at lambda_method(Closure , Shaper ) at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func2 constructEntityDelegate,EntityKey EntityKey,EntitySet EntitySet)在lambda_method(闭包,Shaper)位于System.Data.Entity.Core.Common.Internal.Materialization.Cordinator1.ReadNextElement(Shaper shaper) at System.Data.Entity.Core.Common.Internal.Materialization.Shaper1.SimpleEnumerator.MoveNext()位于System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1源)位于Project.Services.UserService.FindById(Int64 userId)

我在MVC项目中使用Asp.net Identity。

我的用户类类似:

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
....
}

用户经理:

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"));
}
}

用户服务:

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..
}

注册Autofac:

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();
}
}

我还注意到,这个错误不仅影响用户,还会影响其他一些实体!

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

我正在使用Azure SQL、Azure web服务和Autofac。

这里也有同样的问题。这种情况发生在中高需求的情况下。我不知道该怎么办了。我每天回收5次。

我找不到任何标准。该异常引发了许多不同的方法。没有标准。看起来完全是随机的。

我似乎试图在DB上检索信息,但它总是返回空白数据,所以当它试图将空数据强制转换到模型时会抛出错误。

相关内容

  • 没有找到相关文章

最新更新