13

使用带有 .NET MVC 4 的 Code First Entity Framework 我创建了一个新的 Web 应用程序并使用对象填充数据库,如下所示。

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

我想使用我的 UserRepository 表而不是 AccountModel.cs 中的内置 UserContext 类来访问我的用户帐户,因为我无法使用现有的 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:\Users\Unreal\Documents\Visual Studio 2010\Projects\GratifyGaming\GratifyGaming.WebUI\App_Data\Games.mdf”附加为数据库“aspnet-GratifyGaming-20120917185558”。]

[TargetInvocationException: 调用目标抛出异常。] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0

如果我不转到任何 AccountController 驱动的页面,我的应用程序将连接到数据库。如何配置此应用程序以使用我的 UserRepository 表而不是 UsersContext 作为用户成员?

4

1 回答 1

25

从 web.config 中的 DefaultConnectionString 中删除 AttachDbFileName

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

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

 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);
    }
}

在 AccountController.cs 中注释掉 [InitializeSimpleMembership]

 [Authorize]
    //[InitializeSimpleMembership]
    public class AccountController : Controller
于 2012-11-05T06:47:09.933 回答