每次我尝试将用户附加到组(或创建组)时都会收到此错误。
这是 GroupController :
public class GroupsController : Controller
{
private Context db = new Context();
[HttpPost]
public ActionResult Create(Group group)
{
if (ModelState.IsValid)
{
group.owner = db.Users.Attach((User)Session["user"]);
//current user stored in session
db.Groups.Add(group);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(group);
}
}
变量 Session["user"] 在登录时设置,这里是 AccountController 代码:
public class AccountController : Controller
{
private Context db = new Context();
[HttpPost]
public ActionResult LogOn(LoginTemplate login, string returnUrl)
{
User result = db.Users.Where(m => m.email == login.email).Where(m => m.password == login.password).SingleOrDefault();
if (result != null)
{
Session["logged"] = true;
Session["user"] = result;
return RedirectToAction("Index", "Home");
}
}
}
这是我的上下文:
public class Context : DbContext
{
public Context() : base("name=myContext")
{
}
private static Context _instance;
public DbSet<User> Users { get; set; }
public DbSet<Group> Groups { get; set; }
//I tried to use this method in order to always get the same context but does not work
public static Context getContext()
{
if (_instance == null)
{
_instance = new Context();
}
return _instance;
}
}
这是 User.cs
public class User
{
[Key]
public int userId { get; set; }
[Display(Name="Firstname")]
public string firstname { get; set; }
[Display(Name = "Lastname")]
public string lastname { get; set; }
public virtual ICollection<Group> membership { get; set;}
}
这是 group.cs :
public class Group
{
[Key]
public int idGroup { get; set; }
public string name { get; set; }
public User owner { get; set; }
public virtual ICollection<User> members { get; set; }
}
我试图在我的上下文中做一个“单例”(总是在每个控制器中重用相同的上下文)但是当我这样做时,我收到“Db closed”错误消息......