ASP.NET MVC 4とSQL Server 2008でWebアプリケーションを開発しましたが、ContextManagerクラスを作成して、すべてのページに1つのデータベースコンテキストしか持たないようにしました。DbContextが破棄されました
public static class ContextManager
{
public static HotelContext Current
{
get
{
var key = "Hotel_" + HttpContext.Current.GetHashCode().ToString("x")
+ Thread.CurrentContext.ContextID.ToString();
var context = HttpContext.Current.Items[key] as HotelContext;
if (context == null)
{
context = new HotelContext();
HttpContext.Current.Items[key] = context;
}
return context;
}
}
}
これは、ページのほとんどで正しく動作しますが、登録ページに何かがうまくいかないと、私の状況は次のエラーで退陣行って:私は例外だ_db.Contacts.Add(contact);
ラインで
The operation cannot be completed because the DbContext has been disposed.
public ActionResult Register (RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
new
{
Email = model.Email,
IsActive = true,
Contact_Id = Contact.Unknown.Id
});
//Add Contact for this User.
var contact = new Contact { Firstname = model.FirstName, LastName = model.Lastname };
_db.Contacts.Add(contact);
var user = _db.Users.First(u => u.Username == model.UserName);
user.Contact = contact;
_db.SaveChanges();
WebSecurity.Login(model.UserName, model.Password);
。
しかしに
HotelContext _db = ContextManager.Current;
を変更することにより、ContextManagerを使用せず:
HotelContext _db = new HotelContext();
問題が解消しました。しかし私は私自身のContextManagerを使う必要があります。何が問題ですか?
ユーザーを作成した後に問題が発生し、私のdbも確かめるためにWebSecurity.CreateUserAndAccountが正常に処理されていますが、_db.Contacts.Add(contact)で処理されています。私は例外がある。 –
@ ken2kの場合、ContextManagerはHttpContext.Current.ItemsにDbContextを格納しているので、リクエストごとに新しいインスタンスになります。 – mendel