2011-03-15 37 views
0

去這是我的控制器我的代碼:如何測試,如果我的LINQ查詢通過

MGEntities db = new MGEntities(); 
[HttpPost] 
    public ActionResult Register(RegisterModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      // Attempt to register the user 
      MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email); 

      if (createStatus == MembershipCreateStatus.Success) 
      { 

       FormsService.SignIn(model.UserName, false /* createPersistentCookie */); 
       MembershipUser myObject = Membership.GetUser(); 
       Guid UserID = (Guid)myObject.ProviderUserKey; 

       MyProfile profile = new MyProfile(); 
       profile.Address = model.Address; 
       profile.City = model.City; 
       profile.Zip = model.Zip; 
       profile.State = model.State; 
       profile.UserId = UserID; 

       Debug.Write(profile.State); 

       db.aspnet_Profiles.Add(profile); 
       return RedirectToAction("Index", "Home"); 
      } 
      else 
      { 
       ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus)); 
      } 
     } 

這是我的我的資料類:執行LINQ查詢

namespace MatchGaming.Models 
{ 
    [Bind(Exclude = "ProfileId")] 
    public class MyProfile 
    { 
     [Key] 
     [ScaffoldColumn(false)] 
     public int ProfileId { get; set; } 

     public Guid UserId { get; set; } 

     [DisplayName("Address")] 
     public string Address { get; set; } 

     [DisplayName("City")] 
     public string City { get; set; } 

     [DisplayName("Zip")] 
    public string Zip { get; set; } 

    [DisplayName("State")] 


    public string State { get; set; } 
} 
} 

後,我查看我的數據庫並沒有添加任何內容我正在爲我的實體使用POCO。這裏是我的課:

namespace MatchGaming.Models 
{ 
    public class MGEntities : DbContext 
    { 
     public DbSet<MyProfile> aspnet_Profiles { get; set; } 
    } 
} 

我基本上只是不明白爲什麼它不添加到數據庫中,如果那裏有一個方法可以讓我檢查,如果查詢經歷了正確與否,或者如果任何人都可以看到這個問題。謝謝!

+0

你試過調試器嗎? – SLaks 2011-03-15 03:49:12

+0

是的,我調試,並沒有錯誤 – anthonypliu 2011-03-15 04:00:20

回答

0

嘗試

db.aspnet_Profiles.Add(profile); 
db.SaveChanges(); 
+0

我試過這個,但它沒有工作:( – anthonypliu 2011-03-15 03:46:04

0

你濫用EF。

EF上下文不是線程安全的,不能跨請求重用。
您需要爲每個請求創建一個單獨的上下文(MGEntities),方法是在控制器中以using語句創建它。您還需要致電SaveChanges()

+0

你能給我一個這樣的代碼示例? – anthonypliu 2011-03-15 03:50:32

+0

@anthin:'使用(var db = new MGEntities()){...} ' – SLaks 2011-03-15 03:55:50

+0

我試過了,仍然沒有運氣它沒有插入到數據庫中,也沒有給我任何錯誤。也許我沒有正確連接到我的數據庫? – anthonypliu 2011-03-15 03:59:54