【问题标题】:How to send data in multiple db tables?如何在多个数据库表中发送数据?
【发布时间】:2015-11-10 12:29:56
【问题描述】:

我创建了 web api 2 项目,该项目创建了一个本地数据库,其中有一个表“AspNetUser”。我已将这些表与我自己的数据库合并。在我的数据库中,我有一个“员工信息”表,它将存储员工的所有信息,除了他的电子邮件、密码和用户名,所有其他信息都将存储在“员工信息”表中。

这是注册用户的预写代码:

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

这是我自己注册用户的逻辑:

 [ResponseType(typeof(EmployeeInformation))]
        [ActionName("EmployeeInfo")]
        [DeflateCompression]
        public IHttpActionResult PostEmployeeInformation(EmployeeInformation EmployeeInfo)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.EmployeeInformations.Add(EmployeeInfo);
            db.SaveChanges();

那么我如何在“AspNetUser”表中存储电子邮件、密码和用户名,以及在“EmployeeInformation”表中存储所有其他信息(姓名、父亲姓名、dob 等)。 谢谢。

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-identity asp.net-identity-2


    【解决方案1】:

    只需添加ApplicationUserEmployeeInformation 实体之间的关系:

    public class ApplicationUser: IdentityUser
    {
        // other properties
    
        public int EmployeeInformationID {get;set;}
        public virtual EmployeeInformation EmployeeInformation {get;set;}
    }
    

    EmployeeInformation 类做同样的事情

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

    【讨论】:

    • 感谢您的回答,我想再问一件事我的“员工信息”表中已经有一个 UserID 字段,该字段将存储“AspNetUser”表中的用户 ID,所以我需要添加所有这些代码,或者是否有任何其他方式可以从 Account Controller 的 Register 方法获取用户的 ID,并在“PostEmployeeInformation”方法中使用该 ID 来存储剩余信息。谢谢。
    • 您可以从注册操作中获取所有额外数据,而不是使用单独的方法。但是如果你想这样做,你可以通过调用User.Identity.GetUserId() 方法来获取当前用户ID。只需在调用此方法之前强制您的用户登录即可。
    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 2015-02-09
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    相关资源
    最近更新 更多