Asp.net mvc 4 如何在多个db表中发送数据?
我已经创建了WebAPI2项目,它创建了一个本地数据库,其中有一个表AspNetUser。我已将这些表与我自己的数据库合并。在我的数据库中,我有一个“员工信息”表,该表将存储除电子邮件、密码和用户名之外的所有员工信息,所有其他信息将存储在“员工信息”表中 这是注册用户的预写代码:Asp.net mvc 4 如何在多个db表中发送数据?,asp.net-mvc-4,asp.net-identity,asp.net-identity-2,Asp.net Mvc 4,Asp.net Identity,Asp.net Identity 2,我已经创建了WebAPI2项目,它创建了一个本地数据库,其中有一个表AspNetUser。我已将这些表与我自己的数据库合并。在我的数据库中,我有一个“员工信息”表,该表将存储除电子邮件、密码和用户名之外的所有员工信息,所有其他信息将存储在“员工信息”表中 这是注册用户的预写代码: [AllowAnonymous] [Route("Register")] public async Task<IHttpActionResult> Register(Regi
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email};
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var currentUser = UserManager.FindByName(user.UserName);
var roleresult = UserManager.AddToRole(currentUser.Id, model.SelectedRole);
}
else if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
那么,我如何在AspNetUser表中存储电子邮件、密码和用户名,以及在EmployeeInformation表中存储所有其他信息name、fathername、dob等呢。
谢谢。只需添加ApplicationUser和EmployeeInformation实体之间的关系:
public class ApplicationUser: IdentityUser
{
// other properties
public int EmployeeInformationID {get;set;}
public virtual EmployeeInformation EmployeeInformation {get;set;}
}
对EmployeeInformation类执行相同的操作
现在,您有了seprate类,用于用户的额外信息,例如,您可以编写:
public IHttpActionResult PostEmployeeInformation(EmployeeInformation employeeInfo)
{
employeeInfo.UserID="your desired user id, current user id for example";
db.EmployeeInformations.Add(employeeInfo);
db.SaveChanges();
}
谢谢你的回答,我想再问一件事,我的员工信息表中已经有一个UserID字段,它将存储AspNetUser表中用户的ID,那么,我是否需要添加所有这些代码,或者是否有其他方法可以从Account Controller的Register方法获取用户ID,并在PostEmployeeInformation方法中使用该ID来存储剩余信息。谢谢。您可以从register操作中获取所有额外数据,而不是使用单独的方法。但如果您想这样做,您可以通过调用user.Identity.GetUserId方法来获取当前用户id。只需在调用此方法之前强制用户登录即可。
public class EmployeeInformation
{
// other properties
public string UserID {get;set;}
public virtual ApplicationUser User {get;set;}
}
public IHttpActionResult PostEmployeeInformation(EmployeeInformation employeeInfo)
{
employeeInfo.UserID="your desired user id, current user id for example";
db.EmployeeInformations.Add(employeeInfo);
db.SaveChanges();
}