我在sql server数据库中有一个表。我正在尝试使用实体框架将数据插入到表中,但它没有按预期工作。
表
CREATE TABLE [dbo].[UserCompletedWorkouts] (
[Id] INT NOT NULL IDENTITY(1,1),
[UsersName] VARCHAR (50) NULL,
[WorkoutId] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
模型
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; }
}
}
控制器
public ActionResult Index(int Id)
{
db.ViewWorkout.Add(new ConfirmedWorkoutModel() { WorkoutId = Id, UsersName = User.Identity.Name});
return View(db.ViewWorkout.ToList());
}
答案 0 :(得分:2)
您需要在上下文中调用SaveChanges()...
db.ViewWorkout.Add(new ConfirmedWorkoutModel() { WorkoutId = Id, UsersName = User.Identity.Name});
db.SaveChanges();
return View(db.ViewWorkout.ToList());