سؤال

I have a table in a sql server database. I am trying to insert data into the table using entity framework but it's not working as expected.

Table

CREATE TABLE [dbo].[UserCompletedWorkouts] (
[Id]        INT          NOT NULL IDENTITY(1,1),
[UsersName] VARCHAR (50) NULL,
[WorkoutId] INT          NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

Model

   public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }
    public DbSet<ConfirmedWorkoutModel> ViewWorkout { get; set; }
}
    [Table("UserCompletedWorkouts")]
public class ConfirmedWorkoutModel
{
    public int Id { get; set; }
    public string UsersName { get; set; }
    public int WorkoutId { get; set; }
}

}

Controller

        public ActionResult Index(int Id)
    {
        db.ViewWorkout.Add(new ConfirmedWorkoutModel() { WorkoutId = Id,  UsersName = User.Identity.Name});
        return View(db.ViewWorkout.ToList());
    }
هل كانت مفيدة؟

المحلول

You need to call SaveChanges() on the context...

    db.ViewWorkout.Add(new ConfirmedWorkoutModel() { WorkoutId = Id,  UsersName = User.Identity.Name});
    db.SaveChanges();
    return View(db.ViewWorkout.ToList());
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top