gpt4 book ai didi

c# - 实体类型 ApplicationUser 不是当前上下文模型的一部分,具有自定义用户存储的 DB First

转载 作者:行者123 更新时间:2023-11-30 22:05:13 26 4
gpt4 key购买 nike

因此,我正在现有数据库之上构建一个应用程序,我对其更改的权限有限(想法是尽可能少地更改数据库架构)。这是一个 MVC 5 应用程序,试图将身份系统与自定义用户存储一起使用到 MySQL 数据库。

问题:尝试在注册方法中通过自动生成的 AccountController 注册用户时出现以下异常:

IdentityResult result = await UserManager.CreateAsync(user, model.Password); 

System.InvalidOperationException: The entity type ApplicationUser is not part of the model for the current context. at System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType) at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet
1.get_InternalContext() at System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider()
at System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable
1 source, Expression1 predicate, CancellationToken cancellationToken)
at System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable
1 source, Expression1 predicate)
at Microsoft.AspNet.Identity.EntityFramework.UserStore
6.d__6c.MoveNext()

我尝试过的:

  1. 我已经尝试更改帐户 Controller 的 UserManager 实例化 HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();new ApplicationUserManager(new UserStoreService(new Entities()));这解决了眼前的问题,让我注册。但是,这会在稍后尝试重置密码时导致问题,并且我遇到另一个我无法解决的问题,因为我获得了无效的用户 token (尽管我可以确认用户 token 在我使用时可以正常工作HttpContext.GetOwinContext... 用户管理器的版本
  2. 有几篇关于从自动生成的连接字符串更改连接字符串的帖子,如下所示:

<add name="Entities" connectionString="metadata=res://*/Models.tools.csdl|res://*/Models.tools.ssdl|res://*/Models.tools.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=localhost;user id=user;password=***;persistsecurityinfo=True;database=db&quot;" providerName="System.Data.EntityClient" />

像这样的普通连接字符串: <add name="Entities" connectionString="server=localhost;user id=user;password=***;persistsecurityinfo=True;database=db" providerName="MySql.Data.MySqlClient" /> .由于无意的代码优先异常,这很快就会爆炸。然后在路上出现了一些其他问题,这些问题似乎呈螺旋形上升(在解决了 table 上没有声明的 key 等问题之后)。我愿意接受这方面的建议,但宁愿不必走这条路。

下面是与设置相关的代码。任何想法我还可以在这里遗漏什么?或者是用连接字符串的想法解决这个问题的唯一方法?

谢谢!

设置我首先对现有的 MySQL 数据库使用数据库 (EDMX)。跟随 this to change the primary key for users to an int ,我有一个自定义用户存储服务附加到我的数据库和用户表。

DbContext 设置(我修改了自动生成的文件以尝试使用身份系统):

public partial class Entities : IdentityDbContext<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>// DbContext
{
public Entities()
: base("name=Entities")
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}

public static Entities Create()
{
return new Entities();
}

//DbSets are here
}

应用程序用户.cs:

public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim> // IUser<int>//IdentityUser
{
//custom properties are here

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{

var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here

return userIdentity;
}
}

应用程序用户管理器.cs

public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
: base(store)
{ }

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStoreService(context.Get<Entities>()));

// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};

// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};

manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;

manager.EmailService = new EmailService();

var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity")) { TokenLifespan = TimeSpan.FromHours(24) };
}
return manager;
}
}

UserStoreService.cs

 public class UserStoreService : UserStore<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim> //, IUserStore<ApplicationUser, int>, IUserPasswordStore<ApplicationUser, int>, IUserEmailStore<ApplicationUser, int>, IUserLockoutStore<ApplicationUser, int>, IUserSecurityStampStore<ApplicationUser, int>
{
private Entities _db; // = new Entities();

public UserStoreService(Entities db) : base(db)
{
_db = db;
}

public override Task CreateAsync(ApplicationUser user)
{
var profile = new ffs_profile {
//set props here
};

_db.ffs_profile.Add(profile);
return _db.SaveChangesAsync();
}

public async override Task<ApplicationUser> FindByNameAsync(string userName)
{
var profile = await _db.ffs_profile.Where(u => u.email == userName).FirstOrDefaultAsync();

ApplicationUser user = null;
if (profile != null)
user = ToApplicationUser(profile);

return user;
}

private ApplicationUser ToApplicationUser(ffs_profile profile)
{
return new ApplicationUser
{
//set properties here

};
}
public override Task<string> GetPasswordHashAsync(ApplicationUser user)
{
if (user == null)
{
throw new ArgumentException("null user");
}

return Task.FromResult(user.PasswordHash);
}

public override Task<bool> HasPasswordAsync(ApplicationUser user)
{
return Task.FromResult(user.PasswordHash != null);
}

public override Task SetPasswordHashAsync(ApplicationUser user, string passwordHash)
{
return Task.Run(() =>
{
if (passwordHash == null)
throw new ArgumentNullException("passwordHash");
if (string.IsNullOrWhiteSpace(passwordHash))
throw new ArgumentException("passwordHash cannot be null, empty, or consist of whitespace.");
user.PasswordHash = passwordHash;

});
}

public override async Task<ApplicationUser> FindByIdAsync(int userId)
{
var profile = await _db.ffs_profile.Where(u => u.profile_id == userId).FirstOrDefaultAsync();

ApplicationUser user = null;
if (profile != null)
user = ToApplicationUser(profile);

return user;
}

public override Task<string> GetSecurityStampAsync(ApplicationUser user)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<string>(user.SecurityStamp);
}
public override Task SetSecurityStampAsync(ApplicationUser user, string stamp)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
user.SecurityStamp = stamp;
return Task.FromResult<int>(0);
}
}

最后,帐户 Controller 的相关部分:

 public class AccountController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;

public AccountController()
{
}

public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
{
UserManager = userManager;
SignInManager = signInManager;
}

public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
// other autogenerated methods
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
//set props here
};
try
{
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);


return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.ToString());
}

}
return View(model);
}
}

最佳答案

令我懊恼的是,我不得不选择上面的选项 2。我将我的连接字符串更改为类似于常规连接字符串(见上文),然后不得不重写一些我之前没有处理过的 UserManager 方法(例如 manager.GetRolesAsync()manager.CreateIdentityAsync)。我现在可以注册、重设密码等。

关于c# - 实体类型 ApplicationUser 不是当前上下文模型的一部分,具有自定义用户存储的 DB First,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42028014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com