Save UserID of a user logged in a specific colmna of the Data Base

1

I need to save the ID of the user who has logged in the column named "CreatedBy", but I can not write the correct query.

Each time a "FitnessGoal" entity is created , the identity data plus the User ID will be saved in the DB:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Name,Goal,StartDate,FinishDate,Weight")] FitnessGoals fitnessGoals)
        {

            var user = UserManager.FindById(User.Identity.GetUserId());

            if (ModelState.IsValid)
            {
                db.FitnessGoals.Add(fitnessGoals);

                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(fitnessGoals);
        }

Class FitnessGoal :

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FitnessWebApplication.Models
{
    [Table("FitnessGoals")]
    public class FitnessGoals
    {
        /*public List<string> Goals ;

        public FitnessGoals() { this.Goals.Add("Bulk"); this.Goals.Add("Cut"); }*/

        [Key]
        public int ID { get; set; }

        public string CreatedBy { get; set; }

        public string Name { get; set; }

        public string Goal { get; set; }


        [DataType(DataType.Date)]
        [Column(TypeName = "DateTime2")]
        public DateTime StartDate { get; set; }

        [Column(TypeName = "DateTime2")]
        [DataType(DataType.Date)]
        public DateTime FinishDate { get; set; }

        public int Weight { get; set; }

        public enum Goals
        {
            Bulk,
            Cut
        }
    }
}
    
asked by Bryan Romero 17.08.2018 в 22:13
source

1 answer

3

Considering that you already have the object fitnessGoals with its properties defined from the client, internally what is needed is to add one more property, therefore, here the code:

var user = UserManager.FindById(User.Identity.GetUserId());

if (ModelState.IsValid) {
    //La siguiente línea determina a la propiedad CreatedBy y le asigna el valor del usuario.
    fitnessGoals.CreatedBy = user; //Asumiendo que esta variable contiene el UserId.
    //Esta línea se encarga de agregar el elemento a la tabla FitnessGoals.
    db.FitnessGoals.Add(fitnessGoals);
    //Finalmente Entity Framework guarda los cambios en la base de datos.
    db.SaveChanges();
    return RedirectToAction("Index");
}
    
answered by 17.08.2018 / 23:05
source