我打开了Asp.Net Mvc 4 Internet App模板,并为我的数据库设置了连接字符串,如下所示:
:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=ALI-PC\;Initial Catalog=OsosPlusDb;Persist Security Info=True;User ID=sa;Password=sa;" providerName="System.Data.SqlClient" />
</connectionStrings>
我运行项目,点击注册按钮。我像这样创建了一个新用户:
当我点击注册以发布时,我会得到这个错误:
但它确实在数据库中创建了一个新用户,并且没有创建 membership_user (Membership 表不包含添加的用户信息):
我找不到问题所在。有时候不会出现错误。
更新
异常快照如下:
AcoountModel:
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
[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 UsersContext())
{
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);
}
}
}
}
最终编辑和总结
问题出在字符“i”上。如果我不使用“i”,一切都正常。但是当我使用它时,就会出现错误。我该如何解决这个问题。