2012-11-18 28 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)变更注册视图和模型传递的所有信息需要

当这工作得十分完美,我第一次都快哭了没有奇怪的错误。

祝你好运