I need to save the ID of the user who has logged in in the "CreatedBy" name column, but I can't write the correct query.
Each time a "FitnessGoal" entity is created , the data of said identity 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);
}
Fitness Goal class :
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
}
}
}
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 is the code: