13

在.NET MVC 4中使用Code First Entity Framework我已經創建了一個新的Web應用程序,並用對象填充了數據庫,如下所示。.net MVC簡單的數據庫身份驗證與數據庫

public class GratifyGamingContext : DbContext 
{ 
    public DbSet<Game> Games { get; set; } 
    public DbSet<Genre> Genres { get; set; } 
    public DbSet<UserProfile> UserRepository { get; set; } 
} 

我想用我的UserRepository表,而不是內置的UserContext類從AccountModel.cs我的用戶帳戶訪問,因爲我不能讓與我現有的DbContext的工作。

public class UsersContext : DbContext 
{ 
    public UsersContext() 
     : base("DefaultConnection") 
    { 
    } 

    public DbSet<UserProfile> UserProfiles { get; set; } 
} 

[Table("UserProfile")] 
public class UserProfile 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int UserId { get; set; } 
    public string UserName { get; set; } 
} 

從InitializeSimpleMembershipAttribute.cs構造一個SimpleMembershipInitializer對象時,我的程序總是崩潰。我已經評論了我覺得應該是不相關的代碼。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute 
{ 
    private static SimpleMembershipInitializer _initializer; 
    private static object _initializerLock = new object(); 
    private static bool _isInitialized; 

    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     // Ensure ASP.NET Simple Membership is initialized only once per app start 
     LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); 
    } 

    private class SimpleMembershipInitializer 
    { 
     public SimpleMembershipInitializer() 
     { 
      //Database.SetInitializer<UsersContext>(null); 

      try 
      { 
       using (var context = new GratifyGamingContext()) 
       { 
        if (!context.Database.Exists()) 
        { 
         // Create the SimpleMembership database without Entity Framework migration schema 
         ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); 
        } 
       } 

       WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); 
      } 
      catch (Exception ex) 
      { 
       throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex); 
      } 
     } 
    } 
} 

我的ConnectionString如下:

<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-GratifyGaming-20120917185558;AttachDbFilename=|DataDirectory|\Games.mdf;Integrated Security=True" providerName="System.Data.SqlClient" /> 

調用任何的AccountController頁面WebSecurity.InitializeDatabaseConnect時,我得到了以下錯誤:

[SQLEXCEPTION(0x80131904):目錄查找對於文件 「C:\ Users \ Unreal \ Documents \ Visual Studio 2010 \ Projects \ GratifyGaming \ GratifyGaming.WebUI \ App_Data \ Games.mdf」 操作系統錯誤2失敗(無法檢索 此文件的錯誤。原因:15105)。無法附加文件 'C:\用戶\虛幻\文檔\ Visual Studio的 2010 \項目\ GratifyGaming \ GratifyGaming.WebUI \ App_Data文件\ Games.mdf' 作爲 數據庫 'ASPNET-GratifyGaming-20120917185558']

。 [TargetInvocationException:異常已經通過 目標拋出的調用。] System.RuntimeTypeHandle.CreateInstance(RuntimeType 類型,布爾publicOnly,布爾NOCHECK,布爾& canBeCached, RuntimeMethodHandleInternal &構造函數,布爾& bNeedSecurityCheck)0

如果我沒有去任何AccountController驅動的頁面,我的應用程序就會連接到數據庫。 如何配置此應用程序以使用UserRepository表而不是UsersContext作爲用戶成員資格?

回答

25

從DefaultConnectionString web.config中取出AttachDbFileName

<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-GratifyGaming-20120917185558;Integrated Security=True" providerName="System.Data.SqlClient" /> 

調用WebSecurity.InitialiseDatabase方法中的Global.asax.cs

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 

     AreaRegistration.RegisterAllAreas(); 
     Database.SetInitializer<GratifyGamingContext>(new DatabaseInitializer()); 
     WebApiConfig.Register(GlobalConfiguration.Configuration); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
     AuthConfig.RegisterAuth(); 

     WebSecurity.InitializeDatabaseConnection(
        connectionStringName: "DefaultConnection", 
        userTableName: "UserProfile", 
        userIdColumn: "UserID", 
        userNameColumn: "UserName", 
        autoCreateTables: true); 
    } 
} 

註釋掉[InitializeSimpleMembership]在AccountController.cs

[Authorize] 
    //[InitializeSimpleMembership] 
    public class AccountController : Controller 
+0

在閱讀了幾個stackoverflow的帖子後發現了這一點c涵蓋了問題的不同組成部分。 – TryCatch

+4

所以我們不再需要'InitializeSimpleMembershipAttribute'了嗎? – Ashkan

+0

下面是對這個問題的另一個答案,可能會幫助一些人:http://stackoverflow.com/a/12461447/188246(與上面的答案略有不同) –