我尝试(但未通过)将MVC UserManager
实施到我的网站。我认为我的案子相当微不足道。我有一个User
类(实体框架 - 数据库优先),其中包含所有用户的信息。并非User
的每个用户都可以访问该网站。所以在我的ApplicationUser中有一个指向这个类的链接。在代码中它看起来像这样:
public partial class User
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
}
public class ApplicationUser : IdentityUser
{
public virtual Entities.User UserInfo { get; set; }
public ApplicationUser()
{
UserInfo = new Entities.User();
}
}
在控制器中调用CreateUserAsync
- 方法时,一切都会出错。您可以在下面找到我的控制器代码。
public class AccountController : BaseController
{
public UserManager<ApplicationUser> UserManager { get; private set; }
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var dbUser = new User
{
Firstname = model.FirstName,
Lastname = model.LastName,
Email = model.UserName
};
db.Users.Add(dbUser);
db.SaveChanges();
var appUser = new ApplicationUser(model.UserName);
appUser.UserInfo = dbUser;
try
{
var result = await UserManager.CreateAsync(appUser, model.Password);
}
catch (Exception e)
{
db.Users.Remove(dbUser);
db.SaveChanges();
}
}
}
}
CreateUserAsync
- 方法出现以下错误:The entity type ApplicationUser is not part of the model for the current context.
现在我的问题:
答案 0 :(得分:3)
问题是您尝试将添加到一个DbContext的用户添加到您添加到其他DbContext(由UserManager创建)的ApplicationUser中。
相反,您应该将此作为单个操作执行。就这样做:
var dbUser = new User
{
Firstname = model.FirstName,
Lastname = model.LastName,
Email = model.UserName
};
var appUser = new ApplicationUser(model.UserName);
appUser.UserInfo = dbUser;
try
{
var result = await UserManager.CreateAsync(appUser, model.Password);
}
catch (Exception e)
{
// show error or whatever
}