我有一个项目,其 App_Data 文件夹中包含数据库(SIS.mdf)。 现在我有一个新的 MVC4 项目。我通过右键单击 App_Data 文件夹添加现有项目选项,将该数据库手动添加到新的 App_Data 文件夹中。 之后我做了以下事情:
为新添加的数据库创建 DBcontext
public class SisContext : DbContext { //protected override void OnModelCreating(DbModelBuilder modelBuilder) //{ // modelBuilder.Conventions.Remove<System.Data.Entity.Infrastructure.IncludeMetadataConvention>(); //} public DbSet<User> Users { get; set; } public DbSet<AspNetUser> AspNetUsers { get; set; } public DbSet<Role> Roles { get; set; } public DbSet<BusinessUnit> BusinessUnits { get; set; } public DbSet<LicenseHolder> LicenseHolders { get; set; } public DbSet<License> Licenses { get; set; } public SisContext():base("SIS")//SIS is name of the database { if (HttpContext.Current == null) { Database.SetInitializer<SisContext>(null); } } }
问题 1:现在是否可以与我的 App_Data 文件夹中的数据库(SIS)进行交互,该文件夹完全包含上述相同和更多的表?
如果是,我有一个自定义 MembershipProvider 类,它使用上面的 SisContext 类,我试图通过它来验证用户
public class CodeFirstMembershipProvider : MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
if (string.IsNullOrEmpty(username))
{
return false;
}
if (string.IsNullOrEmpty(password))
{
return false;
}
using (var Context = new SisContext())
{
AspNetUser User = Context.AspNetUsers.FirstOrDefault(Usr => Usr.Username == username);
if (User == null)
{
return false;
}
if (!User.IsApproved)
{
return false;
}
if (User.IsLockedOut)
{
return false;
}
String HashedPassword = User.Password;
Boolean VerificationSucceeded = (HashedPassword != null && Crypto.VerifyHashedPassword(HashedPassword, password));
if (VerificationSucceeded)
{
User.PasswordFailuresSinceLastSuccess = 0;
User.LastLoginDate = DateTime.UtcNow;
User.LastActivityDate = DateTime.UtcNow;
}
else
{
int Failures = User.PasswordFailuresSinceLastSuccess;
if (Failures < MaxInvalidPasswordAttempts)
{
User.PasswordFailuresSinceLastSuccess += 1;
User.LastPasswordFailureDate = DateTime.UtcNow;
}
else if (Failures >= MaxInvalidPasswordAttempts)
{
User.LastPasswordFailureDate = DateTime.UtcNow;
User.LastLockoutDate = DateTime.UtcNow;
User.IsLockedOut = true;
}
}
Context.SaveChanges();
if (VerificationSucceeded)
{
return true;
}
else
{
return false;
}
}
}
}
在我的 Web 配置中,我添加了我的 customMembership 提供商,并且还连接到了我的 SIS 数据库。
当我运行时,我收到支持上下文的模型已更改
错误。
有什么建议可以解决我的案子吗?
最佳答案
在base中传递连接字符串。见下文
public SisContext():base(connectionstring)//SIS is name of the database
{
if (HttpContext.Current == null)
{
Database.SetInitializer<SisContext>(null);
}
}
正确的连接字符串应该在 web.config 中定义。
关于asp.net-mvc - 使用EF连接现有数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17097277/