使用.net mvc 4中的代码优先实体框架,我创建了一个新的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);
}
}
}
}
我的连接字符串如下:
<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\sevelygaming\sevelygaming.webui\app廑data\games.mdf“
操作系统错误2导致失败(无法检索
这个错误。原因:15105)。无法附加文件
'C:\用户\不真实\文档\ Visual Studio
2010\projects\sevelygaming\sevelygaming.webui\app\u data\games.mdf'为
数据库“aspnet-sevelygaming-20120917185558”。]
[targetInvocationException:的目标引发了异常
调用。]system.runtimetypehandle.createInstance(runtimetype
类型,boolean publicOnly,boolean nocheck,boolean&canbecached,
运行时方法handleInternal&ctor,布尔值&bNeedSecurityCheck)+0
如果不转到任何accountcontroller驱动的页面,则应用程序将连接到数据库。
如何将此应用程序配置为使用我的userrepository表而不是userscontext作为用户成员?
最佳答案
从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