我有 asp.net mvc4 项目,其中有学生数据库,也有 .xls 格式的旧数据库,我需要将旧数据库中的所有值迁移到新的 sql server 数据库中。在我的 mvc 项目中,我有成员控制器,其中包括注册新学生的方法。此外,我正在编写控制台应用程序,它解析 .xls 表并通过 Register 方法将所有值插入到我的新数据库中。
控制台应用程序:
static void Main(string[] args)
{
string con = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MigrateExelSql\Include\TestDb.xlsx; Extended Properties=Excel 12.0;";
MembershipController mc = new MembershipController();
Student student = new Student();
student.Username = null;
student.Password = "password";
student.Email = null;
student.EntryYear = 2014;
student.PassportNumber = 0;
student.IsApproved = true;
student.PasswordFailuresSinceLastSuccess = 0;
student.IsLockedOut = false;
using(OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
using(OleDbDataReader dr = command.ExecuteReader())
{
while(dr.Read())
{
string row1Col0 = dr[0].ToString();
Console.WriteLine(row1Col0);
string row1Col1 = dr[1].ToString();
Console.WriteLine(row1Col1);
Console.WriteLine();
student.Username = row1Col0;
student.Email = row1Col1;
try
{
mc.Register(student);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Console.ReadKey();
}
注册方法
public static MembershipCreateStatus Register(string Username, string Password, string Email, bool IsApproved, string FirstName, string LastName)
{
MembershipCreateStatus CreateStatus;
System.Web.Security.Membership.CreateUser(Username, Password, Email, null, null, IsApproved, null, out CreateStatus);
if (CreateStatus == MembershipCreateStatus.Success)
{
using (UniversityContext Context = new UniversityContext(ConfigurationManager.ConnectionStrings[0].ConnectionString))
{
Student User = Context.Students.FirstOrDefault(Usr => Usr.Username == Username);
User.FirstName = FirstName;
User.LastName = LastName;
Context.SaveChanges();
}
if (IsApproved)
{
FormsAuthentication.SetAuthCookie(Username, false);
}
}
return CreateStatus;
}
动作结果 POST
public ActionResult Register(Student student)
{
Register(student.Username, student.Password, student.Email, true, student.FirstName, student.LastName);
return RedirectToAction("Index", "Membership");
}
当我尝试从 Web 应用程序添加学生时,一切正常,但是当我尝试从解析的数据库中添加时,下一行出现错误
System.Web.Security.Membership.CreateUser(Username, Password, Email, null, null, IsApproved, null, out CreateStatus);
在我的Register
方法中,那个invalidAnswer
. 我将null更改为“123456789”,然后下一个错误将是invalidQuestion
,然后我也从null更改为“123456789”。在此之后它告诉我我的无效密码。此外,我将下一行添加到我的web.config
requiresQuestionAndAnswer="false"
.
我不知道为什么它不起作用。有人有什么想法吗?