2012-11-18 50 views
2

我已經創建了一個代碼優先和DbContext的數據庫。安全模型和現有數據庫

但是,這是與新的MVC 4站點上的安全模型數據庫分開的。

我的問題是我如何結合自己的現有數據庫的安全模型還是應該保持獨立的正當理由

例如是對此最好的解決方案 http://blog.spontaneouspublicity.com/including-asp-net-simple-membership-tables-as-part-of-your-entity-framework-model

這將重新創建安全模型和角色,當我第一次運行應用程序。

或者是否有另一種方法來做到這一點。

回答

1

因爲這個原因,我喜歡新的MVC和Simplemembership Provider。您可以非常輕鬆地將您的模型與asp.net帳戶模型相結合。

當您使用默認的互聯網模板時,它會創建一個名爲UsersContext的上下文。要做一些簡單的事情,比如添加額外的字段到UserProfile對象來跟蹤數據庫,你需要做3件簡單的事情。

  1. 屬性添加到模型(在賬戶模式,如果你使用默認的模板)
  2. 在帳戶控制器上的寄存器操作,添加新的領域IE:

    public ActionResult Register(RegisterModel model) 
    { 
        if (ModelState.IsValid) 
        { 
         var db = new UsersContext(); 
         // Attempt to register the user 
         try 
         { 
          WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { FirstName = model.FirstName, LastName = model.LastName, Address = model.Address, Company = model.Company, Phone = model.Phone, Country = model.Country, City = model.City, State = model.State, Zip = model.Zip });    
          WebSecurity.Login(model.UserName, model.Password); 
    
          return RedirectToAction("Index", "Dashboard"); 
         } 
         catch (MembershipCreateUserException e) 
         { 
          ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); 
         } 
        } 
    
        // If we got this far, something failed, redisplay form 
        return View(model); 
    } 
    

請注意新的關鍵字,我從模型中傳遞值並將它們匹配到模型中。 (模型綁定可能或不可能在這裏工作,但我還沒有測試過尚未)

3)變更註冊視圖和模型傳遞的所有信息需要

當這工作得十分完美,我第一次都快哭了沒有奇怪的錯誤。

祝你好運